I've been worrying about this for a while and I can't realize what's really happening. Explanation in code comments. There are 2 versions of an application, one of them throws weird results and the second one does the expected work.
var id = "test1";
$.post("http://fiddle.jshell.net/echo/json/", {"data": "data"}, function(a) {
alert(id); // will throw undefined
var id = "test2";
alert(id); // will throw "test2" as expected
});
$.post("http://fiddle.jshell.net/echo/json/", {"data": "data"}, function(a) {
alert(id); // will throw "test1" as expected
id = "test2";
alert(id); // will throw "test2" as expected
});
I'm not sure if it has something to do with ajax call, or an anonymous function, but this is just the way I discovered this so I better keep it there. Could somebody explain what am I missing? Why does it behave differently when I ommit the var
keyword? You can try everything out here on jsFiddle
Cool, you discovered
hoisting
. MDN explains it as good as anyone:Code sample from MDN link below:
You can see how this will result in the "weird behaviour":
is equivalent to:
Which brings me to the final bit of knowledge I can impart, always declare your variables at the top of your code blocks so this "weird behaviour" is coded into your programs (and never throws you off again):
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting