(creating a separate question after comments on this: 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 ?
If you expect
yto be global, you can just drop thevar yline altogether in your second file.The reasoning behind this is that since you want
yto be global anyway, just treat it like its a global and already declared. JavaScript’s side-effect of making variables global when declared without thevarprefix plays to your favor in this situation. Tested in IE8, this works just fine.Edit: As to why this happens, I’d chalk it up to it just being a bug in a combination of IE’s handling of globals across files and declaration hoisting. Really, though, you should only be declaring any variable, but especially a global, in one place. Your problem can be avoided by following this rule of thumb.