Skip to main content

Command Palette

Search for a command to run...

When to add parentheses to a function in Javascript?

Updated
•1 min read•View as Markdown
When to add parentheses to a function in Javascript?

Have you ever seen a code base with a function being called without parentheses "()"? This is acceptable by any Javascript engine.

Check the following two click event on a button:

document.querySelector('button').addEventListener('click', promptAlert()); // first example - Direct functions exec

document.querySelector('button').addEventListener('click', promptAlert); // second example - Indirect function exec

function promptAlert() {
    alert('Hello World!');
}

The first example is direct executable function and will be executed by the Javascript engine as soon as the engine comes across it when rendering the page. This is surely unappropriated in a click event.

The second example suits any event listeners or callback functions like a click event or a setTimeout function. The Javascript engine will wait for the event to occur to execute the function.

However, in the second example we cannot pass any parameters to the function. And what if there was a parameter in the promptAlert() function? Example:

function promptAlert(name) {
    alert('Hello World! ' + name);
}

We have 2 solutions:

  1. Pass the function inside another function like the code below:
document.querySelector('button').addEventListener('click', function() {
    promptAlert('Mr Smith')
});
  1. Use the .bind method on the function:

The bind() method returns a new function, when invoked, has its this sets to a specific value.

document.querySelector('button').addEventListener('click', promptAlert.bind('Mr Smith'));

More from this blog

I

Is A Web Learning

54 posts