Redeclared javascript global variable overrides old value in IE

Posted by Yousuf Haider on Stack Overflow See other posts from Stack Overflow or by Yousuf Haider
Published on 2010-04-14T05:06:25Z Indexed on 2010/04/14 5:23 UTC
Read the original article Hit count: 317

(creating a separate question after comments on this: http://stackoverflow.com/questions/2634410/javascript-redeclared-global-variable-overrides-old-value)

I am creating a globally scoped variable using the square bracket notation and assigning it a value inside an external js file.

In another js file 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 2 javascript files with the following content : Script1

//create global variable with square bracket notation
window['y'] = 'old';

Script2

//redeclaration of the same variable
var y;

if (!y) y = 'new';

alert(y); //shows New instead of Old in IE

Include these 2 files in your html file

<html>
 <head></head>
 <body>

  <script type="text/javascript" src="my.js"></script>
  <script type="text/javascript" src="my2.js"></script>

 </body>
</html>

Opening this page in Firefox and Chrome alerts 'old' which is the expected behavior. However in IE 8 the page will actually alert 'new'

Any ideas on why this happens on IE ?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about global-variables