简体   繁体   中英

JavaScript code executing after return

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM