Photo by Nubelson Fernandes on Unsplash
Closure in JavaScript
In this blog we are going to understand what closures really are and when and why should we use JavaScript closure.
Closure is a combination of a function bundled together (enclosed) with a reference to it's surrounding state.
The closure give us access to an function's scope from an inner function.
in JavaScript closure created every time when closure get created.
That is if we have a child function within a parent function, the child function has access to the scope of the parent function and also access to the global scope
A closure is a function having access to the parent scope, even after the parent function has closed
The parent function can not access variable of child function whereas the child function can access the parent function.
*/ outer function /*
function greet(name){
function dName(){
console.log("hey "+name);
}
dname();
}
greet(Dj)
output:
hey Dj
Every closure has three scopes: global, local, and block Scope.
Closures (that inner function or function returned by another function) have a reference to their lexical environment during the time of their creation.
Closures can help you create private data, whether itβs a private method or a private variable.
In other way you can also look at closures like whenever you have a function inside another function, then you may have a closure but it can also be Curried functions. You might be thinking what are they now , well that can be the topic for my next blog π.
I hope you understood about closures and now you can also explain someone what really closures are. Thanks for reading my blog , I hope it was helpful. Do share it if you find this useful. That's it in this , blog hope to see you in the next blog π.