Everything You Need To Know About Closures In JavaScript

Not sure if your ex gave you closure, but let’s demystify closures in JS and ace those tricky interview questions.

Bhavya Mehta
4 min readJul 26, 2024

Quickly about me, I am Bhavya Mehta, and I have been working as a Software Engineer for around five years now. I enjoy doing many things apart from coding, and writing is one of them. So here I am trying to share what I have been learning.

Photo by Markus Spiske: https://www.pexels.com/photo/close-up-photo-of-codes-1089440/

What in the world is a closure?

Let’s start with the basics. A closure is like a nested function. It’s when you have a function inside another function, and the inner function uses variables from the outer function. Sounds simple, right? Well, there’s a twist — the inner function remembers and can access those outer variables even after the outer function has finished executing. It’s like a function that has the memory of your girlfriend 😜

Here’s a quick example:

function outerFunc(x) {
let y = 10;
function innerFunc() {
console.log(x + y);
}
return innerFunc;
}

const closure = outerFunc(5);
closure(); // Logs - 15

In this snippet, innerFunc is a closure because it "closes over" the variables x and y from its outer scope.

Why should you care about closures?

Private variables—
Closures allow you to create variables that are accessible only within a specific function scope, effectively making them private. This enhances encapsulation and prevents unintended modifications from outside the function.

function createCounter() {
let count = 0; // Private variable
return function() {
return ++count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
// count is not directly accessible here

Function factories —
Closures enable you to create functions with preset parameters, allowing for more flexible and reusable code. This technique is particularly useful when you need to generate functions with specific configurations.

function multiplyBy(factor) {
return function(number) {
return number * factor;
};
}
const double = multiplyBy(2);
const triple = multiplyBy(3);
console.log(double(5)); // 10
console.log(triple(5)); // 15

Module pattern —
Closures are fundamental to the module pattern in JavaScript, allowing you to create private and public methods and variables. This pattern helps in organizing code, reducing global namespace pollution, and implementing information hiding.

const calculator = (function() {
let result = 0;
return {
add: function(x) { result += x; },
subtract: function(x) { result -= x; },
getResult: function() { return result; }
};
})();

calculator.add(5);
calculator.subtract(2);
console.log(calculator.getResult()); // 3
// result is not directly accessible here

Closure interview questions: The good, the bad, and the tricky

Now that we know what are closures, let’s tackle the interview questions. The most common one goes something like this:

for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}

What do you think this code will output? If you said “3, 3, 3,” congratulations! You’ve just spotted a classic closure trap. The setTimeout function creates a closure, but by the time it executes, the loop has already been completed and i is 3.

But wait! Let’s change var to let . Now what will you get? If you said still “3, 3, 3,” sorry :(
You get "0, 1, 2". Why? Because let creates a new binding for each loop iteration. It's like each iteration gets its personal i to play with.

The var vs. let showdown

Understanding the difference between var and let is crucial for mastering closures:

  • var is function-scoped and gets hoisted. It's like that friend who no matter how late starts from home, but always shows up early to the party.
  • let is block-scoped and respects the boundaries of the ground (i.e., the code block it's in).

This difference is why you get different results when using var versus let in-loop closures.

Closure best practices

  1. Be mindful of performance: Closures keep variables in memory, so use them judiciously.
  2. Avoid creating closures in loops unless you absolutely need to.
  3. Use closures to create private variables and methods when you need data encapsulation.
Photo by Paras Katwal: https://www.pexels.com/photo/computer-with-code-4218883/

Conclusion —

Closures might seem like JavaScript black magic at first, but they’re a powerful tool in your coding arsenal. They allow for elegant solutions to complex problems and are a fundamental concept in JavaScript.

So the next time an interviewer asks about closures, you can lean back, smile confidently, and say, “Ah, closures. Let me tell you about the time I used them to create a function factory…” Your interviewer might just offer you the job on the spot. (Results are not guaranteed, but we are all allowed to dream, right? 😛)

Thank you for taking the time to read this. If you ever wish to talk about anything under the sky or beyond, or have suggestions about my article drop a comment below.

You can also reach out to me on — Telegram | LinkedIn | Instagram

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Bhavya Mehta

Web3 Developer | Freelancer | Writing my heart out here