The function below will return b is not defined
because the compiler will look in the function and then into the global scope in search for a variable b
.
However, I assumed that defining b without the word var
would automatically create a global variable?
Can anyone explain the rules when omitting the word var
?
function foo(a) {
console.log( a + b );
b = a;
}
foo( 2 );
Not using var
in a function for a variable declaration does make it global, but in your case, the JavaScript engine is hitting this line:
console.log( a + b );
before it hits this line:
b = a;
And, that's the line that declares it (globally).
And, because you didn't use var
, the declaration is not hoisted to the top of the code base (which it would have been with var
- you would still not have gotten a value for b
because only the declaration would be hoisted, not the initialization, but it would not have thrown an error), so you get your error.
See more about var
and hoisting here .
In strict mode:
In non-strict mode:
var
creates a local variable and is hoisted to the top of the function Since you are not in strict mode and you try to read b
before you assign a value to it, you get an exception.
Guidelines to follow:
"use strict"
Variables declared this way b = a
are not hoisted, like variables declared with the var
keyword. That means that, at runtime, the compiler reads b, not as undefined (as would happen with var b = a
), but as something that doesn´t exist at all, thus throwing a ReferenceError.
Info on Hoisting: https://developer.mozilla.org/en-US/docs/Glossary/Hoisting
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.