What's wrong with defining JavaScript variables within if blocks?

前端 未结 5 2029
予麋鹿
予麋鹿 2020-12-10 04:31

I have some code like this:

if (condition) {
var variable = blah;
}

if (differentcondition) {
var variable = blah;
}

Is this correct?

5条回答
  •  旧巷少年郎
    2020-12-10 05:13

    Because javascript has something called "Hoisting" which makes your code do things it doesn't look like it should be doing. Basically, that means a javascript interpreter will move all var declarations, regardless of where they are in the body of a function, to the top of the function body. Then it will move all function definitions to the top, just under all the vars. Then it will finish compiling the function.

    Putting a var inside an if statement is not against "the rules" of the language, but it means that, because of var hoisting, that var will be defined regardless of whether the if statement's condition is satisfied.

    Keep in mind also that hoisting does not include the assignment, so as others have pointed out, the var declarations will be moved to the top, and left undefined until they're assigned later.

    This is an example of a feature that must have seemed like a good idea at the time, but it has turned out to be more confusing than helpful.

提交回复
热议问题