Remember self-invoking functions? What is the purpose of this function?
const add = (function () { let counter = 0; return function () {counter += 1; return counter} })(); add(); add(); add(); // the counter is now 3 |
The variable add
is assigned the result of a self-invoking function, which runs once, initializes counter
to 0, and returns a function. This closure allows add
to access and modify the private counter
variable, ensuring it is protected.