0

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 ?

Saurabh Tiwari
  • 4,632
  • 9
  • 42
  • 82
  • 1
    No, a `setTimeout` callback does not run in global scope, unless you’re confusing this with the difference between a function callback and a string callback for `setTimeout`. Have you read the documentation on `let` and understood what the difference between `var` and `let` is? – Sebastian Simon Aug 01 '18 at 10:19
  • What were you expecting? – Plochie Aug 01 '18 at 10:26
  • I had a read here `http://javascriptissexy.com/javascript-variable-scope-and-hoisting-explained/`, which says `setTimeout Variables are Executed in the Global Scope` and I was expecting to get a value for `x` if provided in `window` scope else `undefined` – Saurabh Tiwari Aug 01 '18 at 10:31

1 Answers1

0

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.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151