Phillip Senn
Phillip Senn

Reputation: 47605

Lexical scoping in JavaScript

Why is 100 being logged here instead of 101?

function myFunction() {
   var i=100;
   function f() {
      return i++;
   }
   return f();
};
var X = myFunction();
console.log(X); 

http://jsfiddle.net/PhillipSenn/8fqyh/

Upvotes: 1

Views: 86

Answers (1)

Marcelo Cantos
Marcelo Cantos

Reputation: 185862

Because f() returns the value of i before it is incremented. Use pre-increment (++i) if you want the value after it is incremented.

Also, it's a bit odd to declare f() for no other purpose than to immediately call it. I think what you intended was to return a function that increments i and returns the new value each time it is called. To achieve this, simply return the function, then call console.log(X()) to invoke f() and log the incremented value:

function myFunction() {
   var i=100;
   return function() { return i++; }
};
var X = myFunction();
console.log(X());

Upvotes: 6

Related Questions