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

0

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();

asked Apr 14, 2023 at 19:44
Sign in to add a comment

0 Answers

0
📝 No answers yet!

Be the first to answer this interview question.

Your Answer

Sign in to post your answer and help the community.