JavaScript Interview Questions

23 Questions
JavaScript

JavaScript

Web DevelopmentFrontendBackend

Question 4

What is a closure in JavaScript?

Answer:

A closure is a function that retains access to its lexical scope, even when the function is executed outside that scope. Closures allow for data encapsulation and the creation of private variables. This concept is crucial for maintaining state in asynchronous programming and for creating factory functions.

Here is an example demonstrating a closure:

function outerFunction() {
    var outerVariable = 'I am outside!';

    function innerFunction() {
        console.log(outerVariable); // 'I am outside!'
    }

    return innerFunction;
}

var closure = outerFunction();
closure(); // 'I am outside!'

In this example, innerFunction is a closure that retains access to outerVariable even after outerFunction has finished executing. This allows innerFunction to use outerVariable when it is called.

Recent job openings