4

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?

2
  • I think the x is different inside the function.. easy fix would be to do window.x = 2 Commented Jul 29, 2013 at 10:16
  • 1
    As @dystroy said variable declarations get hoisted to the top of the function scope. So because you have the var x = 3, var x get's hoisted to the top and makes the x = 2 a local variable. If you just put x = 3 (without var) then the console.log will output 2 Commented Jul 29, 2013 at 10:17

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.