Tuesday 12 February 2019

javascript - Why variable hoisting after return works on some browsers, and some not?



alert(myVar1);
return false;
var myVar1;



Above code throws error in IE, FF and Opera stating that return statement has to come in the function. But it works (shows undefined) in Safari and Chrome.



The above code has been written in global scope. Outside all the functions.



Any reason?


Answer



In javaScript Variables are moved to the top of script and then run. So when you run it will do



var myVar1;

alert(myVar1);
return false;


This is because javascript doesnt really have a true sense of lexical scoping. This is why its considered best practise to have all your variables declared at the top of the area they will be used to prevent hoisting causing a problem. JSLint will moan about this.



This is a good article that explains it http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting



The return is invalid. If you want to do a true hoisting example (taken from the link above) do




var foo = 1; 
function bar() {
if (!foo) {
var foo = 10;
}
alert(foo);
}
bar();



This will alert 10



EDIT AFTER COMMENT



Below is my understanding and I have read it somewhere but can't find all the sources that I read so am open to correction.



This Alerts thanks to the differences in the JavaScript JIT. TraceMonkey(http://ejohn.org/blog/tracemonkey/) I believe will take the JavaScript and do a quick static analysis and then do JIT and then try run it. If that fails then obviously nothing works.



V8 doesnt do the static analysis and moves to the JIT then runs so something. Its more akin to python. If you run the script in the Developer console(ctrl+shift+j in windows) in Chrome it will throw an error but also run to give you the alert.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...