An even better question is why not get rid of var and make every variable local to its parent function? To alter globals, use the window object explicitly.
An even better question is why not get rid of var and make every variable local to its parent function? To alter globals, use the window object explicitly.
I agree, but I think the solution is to stop using `var`, the question is how useful `var` really is. `let`'s scoping is what it appears to be, `var`'s is not. So `let` is the better choice.
But in practice, there are many cases when I have to create multiple callbacks in a loop; half the time I forget that, in Javascript, declaring a variable inside a loop does not actually create a variable local to the loop, and so have to keep debugging why all my callbacks are behaving exactly the same.
The let statement appears to adopt Lua-style lexical scoping, which will be a breath of fresh air once I can rely on browser support.
const is a different case, but IMO there's no need to use var when let exists.
JS is used in non-DOM contexts as well. Though, of course, if that big a change is being made, a generic substitute for `window` could also be specified.
Isn't that just |this| at the top level?
In node, there is a name for the default global: "global", which is also the default context. So node gives it a "generic substitute" as the OP suggested. Most people use "this" to make assignments to it, rather than the "global" name, since it is usually accessed from the default context.