0

In this code, nextVal seem to be remembered by the function but i am unable to understand.

var gimmeSomething = (function(){
        var nextVal;

        return function(){
            if (nextVal === undefined) {
                nextVal = 1;
            }
            else {
                nextVal = (3 * nextVal) + 6;
            }

            return nextVal;
        };
    })();

    gimmeSomething();       // 1
    gimmeSomething();       // 9
    gimmeSomething();       // 33
    gimmeSomething();       // 105
  • How much *do* you understand? What exactly do we need to clarify? – deceze Jun 19 '18 at 13:01
  • i know about closures. But i can't understand how closure is working in this code. –  Jun 19 '18 at 13:14
  • There's an *Immediately Invoked Function Expression* `(function() { ... })()` which creates the closure. `gimmeSomething` is the function returned from that IIFE. Better now…? – deceze Jun 19 '18 at 13:15
  • i didn't understand how iife is creating a closure. –  Jun 19 '18 at 13:20

0 Answers0