In this article, we will cover some common interview questions related to closures in JavaScript, along with their answers and examples:
Q1. What is a closure in JavaScript?
Ans. A closure is an inner function that has access to the variables and parameters of its outer function, even after the outer function has returned. It allows the inner function to access and manipulate the variables of the outer function, even when they are out of scope.
Q2. What are the benefits of using closures in JavaScript?
Ans. The benefits of using closures in JavaScript are:
- Encapsulation: Closures allow you to encapsulate private data and methods, preventing them from being accessed or modified from outside the function.
- Data privacy: Closures can be used to create private variables and methods that are inaccessible from outside the function.
- Function factories: Closures can be used to create factory functions that generate new functions with specific parameters.
Q3. Can you give an example of a closure in JavaScript?
Ans. Here is an example of a closure in JavaScript:
function outerFunction() {
const outerVariable = "I am from outer function";
function innerFunction() {
console.log(outerVariable);
}
return innerFunction;
}
const inner = outerFunction();
inner(); // I am from outer function
In the above example, the innerFunction
has access to the outerVariable
even after the outerFunction
has returned. This is because the innerFunction
forms a closure over the outerFunction
.
Q4. How do closures help with data privacy in JavaScript?
Ans. Closures help with data privacy in JavaScript by allowing you to create private variables and methods that are inaccessible from outside the function. Here is an example:
function counter() {
let count = 0;
return {
increment: function() {
count++;
console.log(count);
},
decrement: function() {
count--;
console.log(count);
}
};
}
const myCounter = counter();
myCounter.increment(); // 1
myCounter.increment(); // 2
myCounter.decrement(); // 1
In the above example, the counter
function returns an object with two methods, increment
and decrement
, that can access and manipulate the private count
variable. The count
variable is not accessible from outside the function, providing data privacy.
Q5. What is the difference between a function and a closure in JavaScript?
Ans. A function is a block of code that can be called with parameters and can return a value. A closure is a function that has access to the variables and parameters of its outer function, even after the outer function has returned. In other words, closure is a special kind of function that forms a bridge between the function and the outside world.