Expert Developer JavaScript Question:
Download Job Interview Questions and Answers PDF
How will you explain closures in JavaScript? When are they used?
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();
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 Interview Questions And Answers
PDF
Previous Question | Next Question |
Explain window.onload and onDocumentReady? | Is JavaScript case sensitive? Give an example? |