I just discovered some thing REALLY weird in JavaScript. Now I am not a complete noob when it comes to these matters, though admittedly I am no John Resig, so… riddle me this… what does the following JavaScript output to the Window?
var a = 8; var someFunc = function(){ document.write(a); var a = 8; }; someFunc();
Wrong!
The answer is not 8… it is in fact undefined. Go figure! I have tested this on Ubuntu Firefox, Chrome, Opera: Mac Firefox. What am I missing?
To make this a little more interesting… comment out 2nd “var a = 8;” line and what do you get? 8 Voila!
Anyone?
6 Comments
This is too easy: in JavaScript declaration happens *before* code start running, but initialisation happens when you said so. write method will output undefined because local a was declared, but wasn’t initialised, yet. If you remove var line, then your write method will refer to global a, which is already initialised with “8”.
JavaScript looks ahead in the scope of the function you are defining for var statements, and uses those var statements to add symbols to the symbol table… in this case the variable ‘a’. Because there is now an ‘a’ variable in the scope of the function, that trumps the global ‘a’ variable, however at the time ‘a’ is being used it does not yet have a defined value since the assignment is still dynamic and runtime.
That is how variable scoping works in js… What you wrote is the equivalent of:
var a = 8;
var someFunc = function(){
var a;
document.write(a);
a = 8;
};
someFunc();
So basically a is undefined when you call document.write.
Thanks guys. Yes I could definitely see what it was doing in terms of the behavior, creating variables before execution, but I was definitely surprised to learn that JavaScript does this at all.
Yeah, this behavior is called “hoisting”. It’s documented in the standard. For more detail, check out what I learned and wrote about it here: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting
Ah it has a name! Thanks Ben
One Trackback
[...] what does the following JavaScript output to the Window? … Continue reading here: Weird Var Behavior in JavaScript – Weird Var Behavior in … Share and [...]