Parentheses in Function Declarations vs. Invocations
In JavaScript, the distinction between function declarations and invocations appears in their syntax. While function declarations end with curly braces, function invocations end with parentheses.
Consider the following example:
var myFunction = function() { setTimeout(myFunction, 1000); } myFunction();
Here, the setTimeout function expects a function reference as an argument. When you write myFunction, you're referencing the function itself. In contrast, myFunction() actually calls the function.
While this seems straightforward, there are exceptions. setTimeout can also accept a function that returns a function, such as in the following code:
function myFunction() { return function() { alert("ohai"); } } // or const myFunction = () => () => alert("ohai");
In this scenario, setTimeout(myFunction(), 1000) would:
This effectively schedules an alert to display every second.
Therefore, the key difference is that when you omit parentheses, you reference the function object itself. When you include parentheses, you invoke the function. This applies to function declarations, such as var myFunction = function() { ... } and function expressions, such as const myFunction = () => { ... }.
The above is the detailed content of When Do Parentheses Matter in JavaScript Function Calls?. For more information, please follow other related articles on the PHP Chinese website!