-1

The code below is for a function that can only be invoked 3 times, the code is correct. What I don't understand quite well is this part:

 var combi = returnIt() + returnIt() + returnIt();

I understand whats happening insight the threet function (and that func is being called up to counter==3) but how does it gets REMEMBERED outside of it? Not sure if I explained clear enough what I mean..

var returnIt = threet(function() {
  return 5;
});

function threet(func){
  var counter = 0;
  return function(){
    if(counter < 3){
        counter++;
        return func();

        }
   }
}
var combi = returnIt() + returnIt() + returnIt();
combi;
juliascoding
  • 195
  • 1
  • 9

1 Answers1

1

This is because of a concept called closures in javascript. Understand it here:

Simple Example

    function add(a){


        return function(b){

            console.log(a + b);
        }


    }

    add(2)(3); //outputs 5

This is what happens when the above function gets executed

1) Global execution context is created with function add, keyword this and outer environment

2) When call to the function add is made with argument 2, execution context of that particular function is created in the execution stack.

3) As and when it returns the function inside it, its execution context is popped of from the stack but somehow javascript is able to retain the value of variable 'a'

4) The returned function is then invoked with argument 3. This function will look out for value of 'a' and will get it as this function sits in the same physical space as that of variable 'a'.

5) This is called as a closure

Rahul Arora
  • 4,397
  • 1
  • 15
  • 22
  • Link only answers are not acceptable here. If you aren't prepared to put some effort into answering...then don't answer and put the link in a comment. – charlietfl May 30 '16 at 18:24