Re:Overview of JavaScript ES6 features
by petersellers on Monday October 24, 2016 @10:13PM
(#12784716)
"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").
[ Parent
| on HN ]
Re:Overview of JavaScript ES6 features
by Roboprog on Wednesday October 26, 2016 @11:19AM
(#12797137)
Close. 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.