Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript code executing after return

Tags:

javascript

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?

like image 448
dhulme Avatar asked Feb 16 '23 18:02

dhulme


1 Answers

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.

like image 78
Denys Séguret Avatar answered Feb 18 '23 11:02

Denys Séguret