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.
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.
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 - 15In 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 hereFunction 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)); // 15Module 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 hereClosure 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:
varis 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.letis 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
- Be mindful of performance: Closures keep variables in memory, so use them judiciously.
- Avoid creating closures in loops unless you absolutely need to.
- Use closures to create private variables and methods when you need data encapsulation.
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? 😛)
If you liked this article you should also give these a chance —
— Top 5 Ways To Use Console.log To Debug Like a Pro
— How To Make Parallel API Calls In JavaScript
— Zustand Or Redux: Which One Is A Better State Management Library