4 ms·
"var" declares function scope, not global scope. If you really want global scope, declare the variable with no keyword preceding it (e.g. "foo = 3").
by petersellers 10y ago
"var" declares function scope, not global scope. If you really want global scope, declare the variable with no keyword preceding it (e.g. "foo = 3").
- Roboprog 10y agoClose. Assigning "foo" without var will look up the lexical scope stack from most nested to global. If nothing exists, it will indeed make a new global. However, if there is a "foo" somewhere in that scope stack, it will update that variable. var a = function () { var foo var b = function () { foo = 3 } b() } a() console.log( foo ) // undefined In the code above, the "foo" in function a is set to 3, rather than creating a global. (changing the "vars" to "lets" would do the same thing, FWIW) Also, "use strict" mode will not let you make a global that way. If in strict mode, you have to put the "var" outside of any function, then assign it (either on that line, or later) to make a global.