#14) Explain Closures in JS❓

✅A Closure is the combination of function enclosed with refrences to it’s surrounding state.
OR
✅A Closure gives you the access to an outer function’s scope from an inner function.
✅Closure are created every time a function is created.
✅It is an abilit…


This content originally appeared on DEV Community and was authored by Mayank Yadav

✅A Closure is the combination of function enclosed with refrences to it's surrounding state.
OR
✅A Closure gives you the access to an outer function's scope from an inner function.
✅Closure are created every time a function is created.
✅It is an ability of a function to remember the variables and function declared in it's outer scope.

image

Let's talk about the above code?
?The function car gets executed and return a function when we assign it to a variable.
var closureFun = car();

?The returned function is then executed when we invoke closureFun:
closureFun();

?Because of closure the output is Audi is expensive??
When the function car() runs, it sees that the returning function is using the variable name inside it:

console.log(name + " is expensive??");

?Therefore car(), instead of destroying the value of name after execution, saves the value in the memory for further reference.

?This is the reason why the returning function is able to use the variable declared in the outer scope even after the function is already executed.

✔This ability of a function to store a variable for further reference even after it is executed, is called Closure.


This content originally appeared on DEV Community and was authored by Mayank Yadav


Print Share Comment Cite Upload Translate Updates
APA

Mayank Yadav | Sciencx (2021-08-11T16:24:51+00:00) #14) Explain Closures in JS❓. Retrieved from https://www.scien.cx/2021/08/11/14-explain-closures-in-js%e2%9d%93/

MLA
" » #14) Explain Closures in JS❓." Mayank Yadav | Sciencx - Wednesday August 11, 2021, https://www.scien.cx/2021/08/11/14-explain-closures-in-js%e2%9d%93/
HARVARD
Mayank Yadav | Sciencx Wednesday August 11, 2021 » #14) Explain Closures in JS❓., viewed ,<https://www.scien.cx/2021/08/11/14-explain-closures-in-js%e2%9d%93/>
VANCOUVER
Mayank Yadav | Sciencx - » #14) Explain Closures in JS❓. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/08/11/14-explain-closures-in-js%e2%9d%93/
CHICAGO
" » #14) Explain Closures in JS❓." Mayank Yadav | Sciencx - Accessed . https://www.scien.cx/2021/08/11/14-explain-closures-in-js%e2%9d%93/
IEEE
" » #14) Explain Closures in JS❓." Mayank Yadav | Sciencx [Online]. Available: https://www.scien.cx/2021/08/11/14-explain-closures-in-js%e2%9d%93/. [Accessed: ]
rf:citation
» #14) Explain Closures in JS❓ | Mayank Yadav | Sciencx | https://www.scien.cx/2021/08/11/14-explain-closures-in-js%e2%9d%93/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.