0

I'm confused as to why the below will output "1".

If I use var to declare a in myFunc that should limit the scope of a to that function.

Calling "a" in the anonymous function (in the setInterval call) is a different function so why is that considered with the scope of myFunc?

Is it only because the function is anonymous? I would expect a to be available to another function unless bind() was used.

myFunc = function(){

    var a = 1;

    var int = setInterval(function () {

        console.log(a);

    }, 5);    

}
Guesser
  • 1,769
  • 3
  • 25
  • 52
  • 1
    This is known as Closure. Here is the link to the doc :https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures – Seblor Jul 12 '19 at 12:21
  • 1
    `var a` limits it to only this functional scope but the callback given to `setInterval` **is** in that functional scope. – VLAZ Jul 12 '19 at 12:22
  • Try to use LET instead of VAR here are some documentation about it https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Instructions/let – Ggs Jul 12 '19 at 13:04

1 Answers1

0

The function bound to setInterval is a closure, when something is unknown in its own scope, it looks in the outer scope, in your case myFunc scope

Shizzen83
  • 3,325
  • 3
  • 12
  • 32