What is a closure in JavaScript?

Answer

JavaScript allows you to declare a function within another function, and the local variables still can be accessible even after returning from the function you called.

In other words, a closure is the local variables for a function which is kept alive after the function has returned.

An example :

function goodMorning(name) {
var text = ‘Good Morning ‘ + name; // local variable
var goodMorningAlert = function() { alert(text); }
return sayAlert;
}

var goodMorningAlert2 = goodMorning(‘Bob’);
goodMorningAlert2();

In the example above, when goodMorningAlert2() will be executed, you will see output as an alert with “Good Morning Bob”.

In short, in JavaScript, if you use the function keyword inside another function, you are creating a closure.

All javascript Questions

Ask your interview questions on javascript

Write Your comment or Questions if you want the answers on javascript from javascript Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---