Function Call Syntax in JavaScript: Parentheses or No Parentheses
When invoking a function in JavaScript, the use of parentheses raises questions about its potential implications. Let's explore the differences between these two syntaxes:
Call with Empty Parentheses:
window.onload = initAll();
In this case, the function initAll() is invoked immediately and its return value is assigned to window.onload. Typically, when no arguments are passed, this approach is not desirable as it assumes that initAll() returns a function.
Call without Parentheses:
window.onload = initAll;
This syntax assigns the function reference itself to window.onload without executing it. This is because in JavaScript, functions are first-class objects that can be assigned and referred to like any other variable. In this case, initAll will be executed when the load event occurs.
Lambda Syntax with Parentheses:
window.onload = () => initAll();
This lambda expression creates a new function that calls initAll() immediately when invoked. Parentheses are required here to ensure that initAll() is called immediately. However, the reference to the outer function is still assigned to window.onload, so initAll will execute on the load event.
The above is the detailed content of JavaScript Function Calls: Parentheses – When Are They Necessary?. For more information, please follow other related articles on the PHP Chinese website!