1

I have a question. Why when I'm using anonymous function and I want to call it immediately i have to do like that:

(() => {console.log('something')})()

But when I want to use it with setTimeout for example, I don't have to use '(' at beginning and '()' at the end?

setTimeout(() => {console.log('something')}, 2000)
Anonymous
  • 835
  • 1
  • 5
  • 21
  • 4
    `setTimeout` calls the function for you. – kelsny Aug 21 '22 at 23:49
  • Check out my answer to this other question: https://stackoverflow.com/questions/13965702/js-whats-the-difference-between-a-closure-and-closure/13965980#13965980 – slebetman Aug 22 '22 at 08:06
  • Note: after reading my answer in the other question above do note that function arguments are expressions by necessity: the result of the code needs to be passed into the function. For example if you do `foo(1+2)` the result of `1+2` must be calculated so that `3` can be passed to `foo()`. This is the answer to your question - it's because when a function declaration is done inside a function argument (eg, first argument to setTimeout) it is already an expression. – slebetman Aug 22 '22 at 08:10

1 Answers1

2

You pass the function as a parameter to setTimeout, rather than calling it right away. That's why you don't need the () at the end

Velimir Tchatchevsky
  • 2,812
  • 1
  • 16
  • 21