I have been doing JS for a while, and is it a little embarrassing to admit that I still don’t fully understand what exactly are closures. Some examples would be appreciated. Thank you!
A closure is a function that has access to its parent scope. Here's an example from W3Schools.
var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
add();
add();
add();
The counter is initially set to 0 and add() function is assigned its return value. This way, the function call would iterate existing value by 1. The output of the third function call would be 3.
I've never seen it explained quite as neatly as the way Jess Telford explains it so I'll just direct you there... :)
Edouard
Web Developer
Hi @fernkul . I'd say that a closure is a function who has access to its outter scope. As each function define a new scope, closure have access to their outter scope :
function test(){ var message = "hello world!"; function write(){ console.log(message); }(); }The function "write" has access to its outter scope: it's a closure. You can relate on this article if you need more info.
Hope it helped :).