Home > Web Front-end > JS Tutorial > When Do Parentheses Matter in JavaScript Function Calls?

When Do Parentheses Matter in JavaScript Function Calls?

Linda Hamilton
Release: 2024-11-25 14:56:11
Original
288 people have browsed it

When Do Parentheses Matter in JavaScript Function Calls?

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();
Copy after login

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");
Copy after login

In this scenario, setTimeout(myFunction(), 1000) would:

  1. Call the myFunction function and store its return value.
  2. Get the function that myFunction returned.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template