What are Closures in JavaScript?
A closure is a function that has access to its own scope, as well as the scope in which it was defined. This means that a function can access variables from its parent function even after the parent function has finished executing.
Uses of Closures
- Data privacy: Closures can be used to create private variables in JavaScript, as the variables are only accessible within the closure.
- Function factories: Closures can also be used to create functions with pre-defined configurations or states.
- Callback functions: Closures are commonly used with callback functions to maintain context and state.
Example of Closures
function outerFunction() { let outerVar = 'I am the outer variable'; function innerFunction() { console.log(outerVar); } return innerFunction; } const closure = outerFunction(); closure(); // Output: I am the outer variable
Interview Questions on Closures
- What is a closure and how is it created in JavaScript?
- Why are closures useful in JavaScript programming?
- How does a closure maintain access to outer variables even after the outer function has finished executing?
- Can you provide an example of using closures to create private variables in JavaScript?
- Explain the concept of function factories using closures.
In conclusion, closures are a powerful and versatile feature in JavaScript that can be used for various purposes such as data privacy, creating reusable functions, and maintaining context in callback functions.