3

I was solving a puzzle on JS and I found this code:

var xx = (function () {
    var e = 0;
    return function () { return e++ }
})();

It was asked what will be the value of xx.

I've googled about funcitons that return function, but could not find anything helpful, I'm not pretty familiar with functions that return function. Please help.

deceze
  • 510,633
  • 85
  • 743
  • 889
Bharat Soni
  • 2,824
  • 6
  • 23
  • 48

3 Answers3

3

yes, it is returning function, and every time you execute this function xx(); it will return an incremented value

alert( xx() ); //will alert 0

alert( xx() ); //will alert 1

alert( xx() ); //will alert 2

Hope this answers the question

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
3

In JavaScript, functions are first-class objects; that is, they can be passed around and assigned to variables like anything else. So in your case xx is simply a reference to the inner function which can be called, passed around further etc.

One benefit of doing so means you can implement private variables like in your example. By defining e inside the outer function, and referencing it inside the inner function, the inner function retains that reference to e even after it is returned. This allows you to call

xx();
xx();
xx();

which will increment and return the value of e each time. You can't override this variable since there's no public reference to it.

Graham
  • 6,484
  • 2
  • 35
  • 39
2

Let's decompose the statements in its constituents:

var xx =(function(){var e = 0; return function(){return e++}})();
  1. var e = 0; assign 0 to e

  2. return function(){return e++;}

    return a function f which:

    2.1 return the value of e

    2.2 increment e by 1

  3. var xx = function(){var e = 0; return function(){return e++}})();

    assign to xx the function f(){ return e++} with scope [e=0]

  4. xx();

    Exec the function f:

    4.1 return the value of e // 0

    4.2 increment e by one // e = 1

    4.3 xx is now the function f(){ return e++;} with scope [e=1]

So, xx is the function which return the internal value of e (starting from 0) and increment e by one.

IF you call xx(); another time, you'll get:

xx(); // returns 1
xx = f(){ return e++;}[e=2] // returns 2 and increment e by one
user278064
  • 9,982
  • 1
  • 33
  • 46