Can anyone explain this (code in global scope)
var a = a || 4 // a exists & is 4
window.a = window.a || 4 // a exists & is 4
window.a = a || 4 // a is undefined error
a = a || 4 // a is undefined error
An explanation of what the difference is between these 4 assignments and why some handle it properly but others don’t.
[Edit] this particular example was tested on the V8 Chrome console.
The
varstatement declares the variable/function in the closest encapsulating scope and sets it toundefined. When there’s notvar, there’s no variable/function declared at all. Therefore the reference error.Some examples.
functionstatement:varstatement: