JavaScript code executing after return
javascript
Solution
No, the code shouldn't output 2 because variable declarations are hoisted so your code is equivalent to
var x = 1;
(function() {
var x;
x = 2; // changes the internal x variable
return;
x = 3; // does nothing because it's not reached
})();
console.log(x); // Outputs the outside x, which is still 1
The line
x = 2;
only changes the internal `x` variable which shadows the outside one.
The scope of a non global variable is the entire function in which it is declared. From the start of this function to its end.
Problem
In the following example, JavaScript seems to be completely ignoring my `return` statement, and just carrying on executing code. ``` var x = 1; (function() { x = 2; return; var x = 3; })(); console.log(x); // Outputs 1 in both Chrome and FF ``` Surely the code should output `2`? If I remove the `var` keyword from `var x = 3`, it outputs `2` as expected. Is there some strange compiler optimization at work here?