What is a closure in JavaScript?

A closure is a function that keeps access to the variables of the place where it was created, even after that outer function has finished.

function makeCounter() {
  let count = 0;
  return function () {
    count++;
    return count;
  };
}

const counter = makeCounter();
console.log(counter());
console.log(counter());
console.log(counter());

Output:

Tutorials Class - Output Window

1
2
3

The variable count is private: only the inner function can change it. Closures are used for private data, counters, callbacks and function factories.


Learn more about the similar topics:
Tutorials
JavaScript Functions
JavaScript Arrow Functions
Constructor Functions in JavaScript
JavaScript this Keyword
Exercises & Assignments
No Content Found.
Interview Questions & Answers
What are arrow functions in JavaScript?
What is the this keyword in JavaScript?
What is the difference between call, apply and bind?
What is the difference between debounce and throttle?
What is the difference between function declaration and function expression?
What is a closure in JavaScript?