Img Credit : [Caspar Camille Rubin] (https://unsplash.com/@casparrubin)
To Simply say, Closure is a feature of a function that allows it to remember all the variables in its lexical scope even after the execution of the function. For an example, When when fire event to access from the DOM , that is also Closure.
Lets a program first.
What is happening there ? lets break.
- We called a function add and this function returned another function inside.
- Now when the function run and finished in addTen variable, it will keep remember the value of a.
- so now we will pass another value 9 as function parameter into AddTen object.
- Now we can see the value is 19.
Interesting ! so how this is happened ? The Magic is When run AddTen function that looks like.
Lets see another example to clear more. We will try count something
Now you can see getcounter always keep remeber the count value and do the inside function operation when you call it.
← Previous postWhat is Javascript CallBack function and how it works ?
Next post →Use of `this` Keyword in Javascript.