Back to all questions

What is a closure in JS?

Devs Hive

Devs Hive

Seen on interview: 4 users

This is probably a must-have interview question, especially for Junior and Middle developers. If you get asked it, your goal is to answer in an unexpected way.

First, explain in simple terms what a closure is.

In simple terms, it is a function's ability to remember the scope in which it was declared.

Let's look at a simple example:

let count = 0;

function createCounter() {
return function () {
// при спробі доступу до count, шукаємо змінну в середині функції
// в середині функції ми її не знаходимо і починаємо шукати вище
// в createCounter змінної теж нема тому ми рухаємось вище
// ми знаходимо count в глобальній області видимості і використовуємо його
count++;

return count;
};
}

const counter = createCounter();

console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3

Once you've answered the question, say BUT there is a nuance here.

If you consider closures in the context of high-load or even data-intensive Node.js projects, careless use of them can lead to memory leaks.

This happens because the Garbage Collector does not clean up objects that are still referenced. And if you keep large objects in a closure, you are quite likely to run into memory problems. So it is worth keeping WeakMap, WeakSet, WeakRef in mind.

Seen on interview?

Comments (1)

Sign in to leave a comment

VT
User
February 20, 2026 at 08:25 AM

Ну тут count знаходиться поза межами батьківської функції. А тому втрачається один з найбільших переваг - інкапсуляція. Саме тому що якісь структури даних інкопсульовані, і можуть виникати stale closures, коли референс зберігається у дочірній функції, але не використовується.