When you redeclared y
with var y;
, it's now undefined, so if(!undefined)
evaluates to true.
Add another alert in your example to see this:
//create global variable with square bracket notation
window['y'] = 'old';
//redeclaration of the same variable
var y;
alert(y); //undefined
if (!y) y = 'new';
alert(y); // new
var
won't initialize a variable twice, but it will overwrite one not initialized the first time (because it's a new, more local variable), which the window['y']
style does, adding it to the window object. Take this for example:
//create global variable with square bracket notation
window['y'] = 'old';
//redeclaration of the same variable
var y;
alert(y); //undefined
alert(window.y); //old
if (!y) y = 'new';
alert(y); //shows New instead of Old
alert(window.y); //still old