Why should I skip parentheses when passing a function as an argument?

I try to wrap my head around why the following code overflows the stack when parentheses are included, but not when they are omitted.

I call this function as an argument to setTimeout, and it works without parentheses, but of course it crashes when I add them. It was my intuition to add a function () after a function. Just hope someone can figure it out for me. When options are optional, and not?

CASE 1:

var a = 1; function foo() { a++; document.write(a); setTimeout(foo(), 2000) }​ // RangeError: Maximum call stack size exceeded 

CASE 2:

 var a = 1; function foo() { a++; document.write(a); setTimeout(foo, 2000) }​ // parens are omitted on foo function and it works. 
+6
source share
2 answers

This question is usually asked first regarding setTimeout , but I think it is important to indicate that the behavior here is not specific to this function. You just need to understand what the brackets do and what it means to leave them.

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 execute the function foo and assign its return value - the number 5 - to one . In the second case, we assign foo ourselves - more precisely, a link to foo - to two . The function is never executed.

With this knowledge and understanding that setTimeout expects function references as its first argument, it should be obvious why your first case fails, but the second works.

Of course, your problem is compounded by the fact that the function you are performing is a recursive call for yourself. This will be done forever - for some definition forever - because there is no base case for completing a recursion.

+10
source

By writing

 foo() 

you are actually calling foo at this point. Which, of course, calls foo () again ... until you do stackoverflow.

In case 2, you effectively pass the “link” to foo, saying “run it in 2 seconds”. Not really a call to foo ().

So use parens when you really want to call it. Not when you want to turn to him.

+9
source

Source: https://habr.com/ru/post/920079/


All Articles