Belhassen Chelbi Nov 14, 2017
What’s a closure?
A closure is a function that returns another function, wich is very simple as a concept and we’ll see a little example that may clarify things for us:
Now, the example I’ve shown isn’t maybe that hard and may not show what’s weird in the closure , just you have to keep in mind that it returns a function (and this last function can return what ever you want).
Now, let’s see another example that shows us how weird and a beautiful a closure is .
Here, the outer and the inner function have different arguments, The outer was assigned to the variable a with a parameter 2, so a is an inner function of an outer function with a parameter x wich is here 2 . Now we need to call with other parameter y that we choose (here 3), so a(3) will multiply 2 (argument of outer function) and 3 (argument of the inner function). Then we’ve assigned it to a variable b and wrote that with document.write to see the result wich is of course 6 .
The closure as you see is weird and require some time to be fully understood.
Practise what you’ve learnt , and you discover more about closures on MDN.