When you use ()
after a function name, you're executing the function. But without it, you're referencing the function instead. That is why line 5 doesn't do anything. The function is not being executed. But line 6 on the other hand is executing the function, which should print "hello" to the console.
The setTimeout
needs a function reference (the callback function), to let it know what to execute after the 1000 ms has passed.
So typing setTimeout(sayHello(), 1000)
executes the sayHello
function directly instead of providing it as a callback. So that will not work as you intend.
Typing setTimeout(sayHello, 1000)
, you're instead providing the function reference instead, to the setTimeout will know what function to execute after the 1000 ms has passed. This is the correct way to do it.