DEV Community

Cover image for #14) Explain Closures in JS❓
Mayank Yadav
Mayank Yadav

Posted on

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


Discussion (0)