skip to Main Content

emphasized textHi I’m learning Javascripts closures and tjis code beahves funny to me:

function Unique_id2() {
    let counter = 0;
    function f() { return counter++; };
    return f();
}

console.log("UID2");
let f = Unique_id2;
console.log(typeof f);
console.log(f());
console.log(f());
console.log(f());
console.log(f());
console.log(f());

the result is:

UID2
functions.js:65 function
functions.js:66 0
functions.js:67 0
functions.js:68 0
functions.js:69 0
functions.js:70 0

which is strangge to me since the counter souhld be incrementsd each time …

can you explain what’s wrong

EDIT

function Unique_id2() {
        let counter = 0;
        function f() { return counter++; };
        return f;
    }

    console.log("UID2");
    let f = Unique_id2;
    console.log(typeof f);
    console.log(Unique_id2()());
    console.log(Unique_id2()());
    console.log(Unique_id2()());
    console.log(Unique_id2()());
    console.log(Unique_id2()());

yields the same result

2

Answers


  1. You’re not returning the closure, you’re just calling it each time you call Unique_id2(). And each time you do that, it resets the counter to 0 and returns that.

    To get an incrementing counter, you have to return the closure, not the result of calling it.

    function Unique_id2() {
        let counter = 0;
        function f() { return counter++; };
        return f;
    }
    
    console.log("UID");
    let f = Unique_id2();
    console.log(typeof f);
    
    console.log(f());
    console.log(f());
    console.log(f());
    console.log(f());
    console.log(f());
    
    console.log("UID2");
    let f2 = Unique_id2();
    console.log(typeof f2);
    console.log(f2());
    console.log(f2());
    Login or Signup to reply.
  2. Even with different names and references, you’re calling Unique_id2 every time.

    And every time it is invoked, the Unique_id2 function initialises the variable counter to 0.

    To achieve what you are trying to do, you need to move the initialisation of counter out of the Unique_id2 scope, like this:

    let counter = 0;
    
    function Unique_id2() {    
        function f() { return counter++; };
        return f;
    }
    
    console.log("UID");
    let f = Unique_id2();
    console.log(typeof f);
    
    console.log(f());
    console.log(f());
    console.log(f());
    console.log(f());
    

    This way the counter variable is initialised only once, and thanks to the closure, the Unique_id2 has access to it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search