code_0:
(calling foo
without parentheses)
function foo(){
console.log(\'hello world\');
}
setTimeout(foo, 2000);
This
setTimeout(foo, 2000)
passes the function foo
and the number 2000
as arguments to setTimeout
. setTimeout(foo(), 2000)
calls foo
and passes its return value and the number 2000
to setTimeout
.
In the first example, you’re not calling the function at all, just passing it as an argument like any other value.
As a simpler example, just log it:
function foo() {
return 5;
}
console.log(foo); // console.log is passed a function and prints [Function]
console.log(foo()); // foo() is called and returns 5; console.log is passed 5
// and prints 5