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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
functiongreet(message){
 
console.log(message);
 
}
 
functiongreeter(name,age){
 
returnname+" says howdy!! He is "+age+" years old";
 
}
 
// Generate the message
 
varmessage=greeter("James",23);
 
// Pass it explicitly to greet
 
greet(message);
 
Thisfunctioncan be better represented by using closures
 
functiongreeter(name,age){
 
varmessage=name+" says howdy!! He is "+age+" years old";
 
returnfunctiongreet(){
 
console.log(message);
 
};
 
}
 
// Generate the closure
 
varJamesGreeter=greeter("James",23);
 
// Use the closure
 
JamesGreeter();

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 ---