Expert Developer JavaScript Question:

How will you explain closures in JavaScript? When are they used?

Tweet Share WhatsApp

Answer:

Closure is a locally declared variable related to a function which stays in memory when the function has returned.

For example:

JavaScript

function greet(message) {
console.log(message);
}

function greeter(name, age) {
return name + " says howdy!! He is " + age + " years old";
}

// Generate the message
var message = greeter("James", 23);
// Pass it explicitly to greet
greet(message);

This function can be better represented by using closures

function greeter(name, age) {
var message = name + " says howdy!! He is " + age + " years old";
return function greet() {
console.log(message);
};

}

// Generate the closure

var JamesGreeter = greeter("James", 23);

// Use the closure

JamesGreeter();

Download Expert JavaScript Developer PDF Read All 150 Expert JavaScript Developer Questions
Previous QuestionNext Question
Explain window.onload and onDocumentReady?Is JavaScript case sensitive? Give an example?