Javascript redeclared global variable overrides old value

Posted by Yousuf Haider on Stack Overflow See other posts from Stack Overflow or by Yousuf Haider
Published on 2010-04-14T02:01:44Z Indexed on 2010/04/14 2:13 UTC
Read the original article Hit count: 438

I ran into an interesting issue the other day and was wondering if someone could shed light on why this is happening. Here is what I am doing (for the purposes of this example I have dumbed down the example somewhat):

  • I am creating a globally scoped variable using the square bracket notation and assigning it a value.
  • Later I declare a var with the same name as the one I just created above. Note I am not assigning a value. Since this is a redeclaration of the same variable the old value should not be overriden as described here: http://www.w3schools.com/js/js_variables.asp

    //create global variable with square bracket notation
    window['y'] = 'old';
    
    
    //redeclaration of the same variable
    var y;
    
    
    if (!y) y = 'new';
    
    
    alert(y); //shows New instead of Old
    
  • The problem is that the old value actually does get overriden and in the above eg. the alert shows 'new' instead of 'old'. Why ?

I guess another way to state my question is how is the above code different in terms of semantics from the code below:

//create global variable 
var y = 'old';

//redeclaration of the same variable
var y;

if (!y) y = 'new';

alert(y); //shows Old

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about global-variables