Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JavaScript Closures

Remember self-invoking functions? What is the purpose of this function?

Example

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

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

// the counter is now 3

Example Explained

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.