javascriptsettimeoutletscopesglobal-scope

Aren't all function in setTimeout executed in global scope?


I thought all the functions in setTimeout are executed in global scope. Then I saw this today:

 for(let x = 0; x < items.length; x++){
          setTimeout(function() {
                console.log(x);
          })
 }

Even with a value for x in global scope/window scope; this code consoles from 0 to 9. What is I am missing here. Isn't this function supposed to run in global scope.

How come using let instead of var changes the former fact ?


Solution

  • The article you quoted is just wrong.

    setTimeout Variables are Executed in the Global Scope

    1) What is a setTimeout variable? Did they mean the "first argument of setTimeout" ?

    2) variables cannot be executed. Their value can be executed (if it is a function)

    3) Something is not "executed in a scope", the scope is determined lexically so for a certain function it is always the same, it does not matter how and where you execute it.

    4) In the snippet below they say that its "executed in the global scope" because this points to window. That has nothing to do with scope, thats context.

    Now to your questions:

    Isn't this function supposed to run in global scope?

    No, it runs in the block scope of the for loop because it is "inside" of that block.

    How come using let instead of var changes the former fact ?

    That has to do with the difference between block / function scope, read on here.