Questions
What are closures and how do you use them in JavaScript?
The Scenario
You are a frontend engineer at a social media company. You are writing a new feature that needs to create a private variable that can only be accessed by a specific function.
The Challenge
Explain what closures are in JavaScript and how you would use them to solve this problem. What are the key benefits of using closures?
A junior engineer might not be aware of closures. They might try to solve this problem by using a global variable, which would not be a very good solution.
A senior engineer would know that closures are the perfect tool for this job. They would be able to explain what closures are and how to use them to create private variables.
Step 1: Understand What Closures Are
A closure is a function that has access to the variables in its outer (enclosing) function’s scope chain. In other words, a closure allows a function to access variables from an outer function, even after the outer function has returned.
Step 2: Create a Private Variable
Here’s how we can use a closure to create a private variable:
function createCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3In this example, the createCounter function returns a new function. This new function has access to the count variable from the createCounter function’s scope, even after the createCounter function has returned.
The Benefits of Using Closures
| Benefit | Description |
|---|---|
| Data Encapsulation | Closures allow you to create private variables that can only be accessed by a specific function. |
| Stateful Functions | Closures allow you to create stateful functions that can remember their state between calls. |
| Partial Application | Closures can be used to create partially applied functions. |
Practice Question
What will be logged to the console?