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.
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
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/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.