1

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?

J.Doe
  • 21
  • 3
  • 1
    The closure in the first example is `() => ...`. Where `setTimeout` is defined doesn't matter. No, a loop is not equivalent to a method. – deceze Sep 02 '18 at 09:41
  • 1
    The loop and the function example is the same, in the loop the relevant part is not the `setTimeout` but the `() => console.log(i)`. So with both `function() { console.log(text); }` and `() => console.log(i)` you defined a function that creates a closure over a variable (`i` or `text`) – t.niese Sep 02 '18 at 09:41
  • A closure is any function that references variables defined in the outer scope. So the anonymous function you're passing to `setTimeout` is a closure because it uses `i`, and `say` is a closure because it uses `text`. – 4castle Sep 02 '18 at 09:43
  • The closure is always the inner function. What it closes over depends on the scope it is in, and changing that is the solution to your problem. A `for (var …) {` does not create its own scope, a `for (let …) {` and a `function(…) {` do create scopes. – Bergi Sep 02 '18 at 12:25

0 Answers0