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
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.
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 variablecounter
to 0.To achieve what you are trying to do, you need to move the initialisation of
counter
out of theUnique_id2
scope, like this:This way the
counter
variable is initialised only once, and thanks to the closure, theUnique_id2
has access to it.