I am trying to wrap my head around as to why the following code results in a stack overflow when the parentheses are included, but do not when they omitted.
I am ca
This question is usually first asked in reference to setTimeout
, but I think it's important to point out that the behavior here isn't specific to that function. You simply need to understand what the parenthesis do and what it means to leave them off.
Assume the following function:
function foo() {
return 5;
}
Consider the following two variable declarations/assignments:
var one = foo();
var two = foo;
What values do these variables have?
In the first case we're executing the foo
function and assigning its return value -- the number 5
-- to one
. In the second case we're assigning foo
itself -- more precisely, a reference to foo
-- to two
. The function is never executed.
With this knowledge and an understanding that setTimeout
expects as its first argument a reference to a function, it should be obvious why your first case fails, but the second one works.
Of course, your problem is exacerbated by the fact that the function you're executing is a recursive call to itself. This will just run forever -- for some definition of forever -- because there's no base case to terminate the recursion.
By writing
foo()
you're actually calling foo at that moment. Which of course then calls foo() again...until you stackoverflow.
In case 2 you're effectively passing a "reference" to foo, saying "run this in 2s". Not actually calling foo().
So use parens when you actually want to invoke it. Not when you want to refer to it.