Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 591
alter Avatar asked Sep 16 '10 10:09

alter


People also ask

Why hoisting does not work with LET and const?

let and const hoisting Variables declared with let and const are also hoisted but, unlike var , are not initialized with a default value. An exception will be thrown if a variable declared with let or const is read before it is initialized.

Are all variables hoisted in JavaScript?

JavaScript Initializations are Not HoistedJavaScript only hoists declarations, not initializations.

Why are function expressions not hoisted?

Function expressions aren't added to the scope at all, hoisted or otherwise. This is because they are being used as a value, as opposed to function declarations, whose purpose is to create functions you can call by name. Because "hoisting" does not exist.

How do you avoid variable hoisting?

Some ways to avoid hoisting are: Use let or const — As explained above, using let or const instead of var would throw an exception and not let the program run, hence helping catch the issue earlier. Use function expressions instead of function declarations.


1 Answers

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 doesn't really have a true sense of lexical scoping. This is why it's considered best practice 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

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 to run it. If that fails then obviously nothing works.

V8 doesn't do the static analysis and moves to the JIT then runs so something. It's 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.

like image 158
AutomatedTester Avatar answered Sep 19 '22 09:09

AutomatedTester