Home >Web Front-end >JS Tutorial >When to Use Parentheses with JavaScript Function References?
When to Use Parentheses and When Not?
In JavaScript, it's crucial to understand when to use parentheses and when not, particularly with function references. Consider the following code:
var myFunction = function() { setTimeout(myFunction, 1000); } myFunction();
Why does the function call in setTimeout not require parentheses, while the last line does?
Nutshell
Detailed Explanation
setTimeout accepts a function reference as an argument. In the first line, setTimeout(myFunction, 1000) passes the function reference without parentheses because it expects a reference.
However, in the last line, myFunction() is actually calling the function. To invoke a function, we use parentheses to execute it. Hence, myFunction() executes the function and therefore requires parentheses.
Exception
There may be instances where setTimeout(myFunction(), 1000) is appropriate, such as when myFunction() returns a function. For example:
function myFunction() { return function() { alert("ohai") } } // Or const myFunction = () => () => alert("ohai")
In this case, setTimeout(myFunction(), 1000):
This results in an alert every second.
Conclusion
Understanding the purpose of parentheses in function references is essential for effective JavaScript programming. By remembering that parentheses indicate a function call, you can correctly use them to invoke functions or pass function references as needed.
The above is the detailed content of When to Use Parentheses with JavaScript Function References?. For more information, please follow other related articles on the PHP Chinese website!