I have been trying to understand closures but every single example I have seen and read all contain the same examples of functions inside functions, but all of the closure problems I face contain functions inside loops.
for (var i = 0; i < 2; i++){
setTimeout(() => console.log(i));
}
Take the above code as an example, setTimeout
is an API method inside the browser and i
is not being passed through.
function sayHello(name) {
var text = 'Hello ' + name;
var say = function() { console.log(text); }
say();
}
sayHello('Joe');
The above frequently used closure example is not the same because I have called setTimeOut
inside a for loop
. setTimeout
is not defined/created inside the function/loop, I am only calling it. It could therefore be defined somewhere else, outside of the function, which goes against closures entirely. What am I missing here o.O
Secondly, I have a for loop
, not a function above another function. Is the variable declaration above the equivalent?