← JavaScript Interview Questions

What is closure in JavaScript?

Asked 2 years ago by Hayk Hovhannisyan


A closure is a function created inside of another function that can have access to the scope of the parent function.

function inc() {
  let counter = 0;
  return function() {
    return ++counter;

const usages = inc();
usages(); // 1
usages(); // 2
usages(); // 3

Note that variable counter from the outer function scope will exists after the execution of inc function. It will be removed from the memory by garbage collector only when the reference to usages variable will be removed.

Answered 2 years ago by Hayk Hovhannisyan