code_0:
(calling foo without parentheses)
function foo(){
console.log(\'hello world\');
}
setTimeout(foo, 2000);
This
The point of confusion here is that you're not realizing that using
foowithout parentheses is not calling the function...it's only referencing it.
foo is the reference to the function itself. To call a function (i.e. actually execute its code) you reference it with parentheses at the end (e.g. foo()). In a practical sense that means:
// references the function itself
// ...you could call one() now and it would run the function foo
var one = foo;
// runs/calls the function, and var two will then be whatever foo returns
var two = foo();
So in the first example you are NOT calling the function. You are passing the function foo to setTimeout. setTimeout will then call it after a delay.
In the second example you called foo immediately and passed whatever foo returns to setTimeout (which setTimeout couldn't do anything with, because that return value likely wasn't another function). So your function was executed immediately and then nothing would have happened (except likely some errors) after setTimeout was done with its delay.