1

I executed the following code:

setTimeout(() => console.log('first'), 0)
console.log('second');

and as expeted got the output (since Javascript acts asynchronously) in the following order:

second
first

But when I changed the first argument of the setTimeout() function like so:

       //notice the ()=> part is removed
        setTimeout(console.log('first'), 0)
        console.log('second');

I get the output in the following order:

first 
second

It is as if Javascripts starts behaving synchronously again after I removed the ()=> part of the first argument.

Can someone explain this?

Keith M
  • 421
  • 1
  • 8
  • 18
  • 1
    `console.log('first')` is not a function; it's the *result* of *calling* `console.log()` (always `undefined`). – Pointy Jan 18 '19 at 18:33
  • 1
    In `foo(bar())` `bar` is always executed first and its return value is passed to `foo`. In your first example you pass a function. In your second example you pass the result of calling `console.log('first')`. This has nothing to do with `setTimeout`. All functions work like that. – Felix Kling Jan 18 '19 at 18:33
  • 2
    why there is a downvote without any explanation? – Hith Jan 18 '19 at 18:35
  • [How can I pass a parameter to a setTimeout() callback?](https://stackoverflow.com/q/1190642/4642212) – Sebastian Simon Jan 18 '19 at 18:35

1 Answers1

1

In the second case console.log('first') is returning undefined which is passed to the setTimeout when you call setTimeout(console.log('first'), 0) like this.

The function reference passed is undefined and at the same time the console.log('first') is also getting executed synchronously.

Therefore there will be no asynchronous behavior in observed output as the setTimeout is not executing anything asynchronously as the supplied function reference is undefined.

Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44