How to define a javascript closure?

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

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

// Result: counter is 3
Copy

September 3rd, 2019

# Javascript Closure

Add to bookmarks

The variable add is assigned the return value of a self-invoking function. The self-invoking function only runs once. It sets the counter to zero (0), and returns a function expression. This way add becomes a function. The "wonderful" part is that it can access the counter in the parent scope.

Tracking with Matomo to improve the UX. See Privacy Policy for more details.