How will you explain closures in JavaScript? When are they used?
Closure is a locally declared variable related to a function which stays in memory when the function has returned.
function greet(message) { console.log(message);}function greeter(name, age) { return name + " says howdy!! He is " + age + " years old";}// Generate the messagevar message = greeter("James", 23);// Pass it explicitly to greetgreet(message);This function can be better represented by using closuresfunction greeter(name, age) { var message = name + " says howdy!! He is " + age + " years old"; return function greet() { console.log(message); };}// Generate the closurevar JamesGreeter = greeter("James", 23);// Use the closureJamesGreeter();
0 Answers
0Be the first to answer this interview question.
Your Answer
Sign in to post your answer and help the community.