Can you please explain to me how this code works?

Hi, I have been recently trying to learn Javascript, and I came accross this code on w3schools website and I’m having a really hard time understanding it.

Here is the code:

var add = (function () {
  var counter = 0;
  return function () {counter += 1; return counter}
})();

add();
add();
add();

as far as i can understand, the code uses a nested function and it’s an anonymous self invoking function but i don’t understand how, when we execute it, the first time we get 1 aas output, then 2 , then 3 and so on. why is that?

Seems to me that is because your adding 1 number each time.
Like you did in school 1+1 makes 2 right next time you add+1 again the 2 becomes a 3.

closure closure closure

Do you mean he forgot to close it with the brackets? UwU

no, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

1 Like

okay, but what is the self invoking function doing in this code?

self-invoking, meaning call itself

1 Like

oh ok. Thanks man. just one last thing. can you explain what this line does?
return function () {counter += 1; return counter}

I’m particularly asking about return function. why did we do that?

Thanks a lot for the help, man

functions can be values in javascript, so add function returns a function, the line you asking about

1 Like

oh ok. Thanks for the help again

1 Like

For the sake of experiment try to run this code:
It is your example with some console logs.

var add = (function () {
  console.log('WRAPPER');
  var counter = 0;
  return function () { console.log('INNER'); counter += 1; return counter}
})();

add();
add();
add();

Open your console in chrome and run with console.trace()

var add = (function () {
  console.trace('WRAPPER');
  var counter = 0;
  return function () { console.trace('INNER'); counter += 1; return counter}
})();

add();
add();
add();

You will see exactly the order of execution of the functions. And the magic behind the scenes. Click on each trace output.

You need to read about ‘Closures’ and Self invoking functions!

Put there a const instead that var, var can be change, const no.