← JavaScript Interview Questions

What is closure in JavaScript?

2
1
Asked 5 years ago by Hayk Hovhannisyan

Answers

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.

0
Answered 5 years ago by Hayk Hovhannisyan