In JavaScript, Does It Make a Difference If I Call a Function With Parentheses

In JavaScript, does it make a difference if I call a function with parentheses?

window.onload = initAll();

This executes initAll() straight away and assigns the function's return value to window.onload. This is usually not what you want. initAll() would have to return a function for this to make sense.

window.onload = initAll;

this assigns the actual function to window.onload - this is possible because in JavaScript, as @Felix says, functions are first class objects - without executing it. initAll will be executed by the load event.

You may also see something like this:

window.onload = () => initAll();

This will create a new function that, when called, will call initAll immediately. Parentheses are necessary here for that "call initAll immediately" part to work. But, because it's wrapped in a function, nothing will execute until that outer function itself is called, and you assign the reference of that outer function to window.onload, so initAll will also be executed on the load event.

Difference of calling a function with and without parentheses in JavaScript

With parentheses the method is invoked because of the parentheses, and the result of that invocation will be stored in before_add.

Without the parentheses you store a reference (or "pointer" if you will) to the function in the variable. That way it will be invoked whenever someone invokes before_add().

If that didn't clear things up, maybe this will help:

function Foo() {

return 'Cool!';

}

function Bar(arg) {

console.log(arg);

}

// Store the >>result of the invocation of the Foo function<< into X

var x = Foo();

console.log(x);

// Store >>a reference to the Bar function<< in y

var y = Bar;

// Invoke the referenced method

y('Woah!');

// Also, show what y is:

console.log(y);

// Now, try Bar **with** parentheses:

var z = Bar('Whut?');

// By now, 'Whut?' as already been output to the console; the below line will

// return undefined because the invocation of Bar() didn't return anything.

console.log(z);

Javascript function call with/without parentheses

setTimeout(foo, 2000) passes the function foo and the number 2000 as arguments to setTimeout. setTimeout(foo(), 2000) calls foo and passes its return value and the number 2000 to setTimeout.

In the first example, you’re not calling the function at all, just passing it as an argument like any other value.

As a simpler example, just log it:

function foo() {
return 5;
}

console.log(foo); // console.log is passed a function and prints [Function]

console.log(foo()); // foo() is called and returns 5; console.log is passed 5
// and prints 5

What is the difference between writing a function with or without parentheses inside a function in jQuery?

Putting parentheses () at the end of a function causes that function to be invoked immediately, and use its return value in the expression.

This code $(document).ready(test); is using test as a callback function. It essentially says: when the document becomes ready, call the function that I'm providing you with (test).

This code $(document).ready(test()); is immediately invoking the function test, having it return a value, and then passing that value to the ready method. It's possible that test is returning a different function here, which in turn will act as the required callback function. It could also just be an error though, with someone inadvertently including the parentheses when they shouldn't have.

Why are parenthesis used to wrap a javascript function call?

This is done for readability.

There isn't a real functional difference between the two examples you've given, but both of them are very close to a simple function declaration, which is different. The parenthesis are added for readability, in order to distinguish them.

Here is what each of your snippets do:

In the first of your two snippets, the first parenthesis will be evaluated as the value of the enclosed function. Then this value will be called as a function. So ultimately the function will be executed, which is probably what you care about.

In your second snippet, the outer parenthesis will be evaluated as containing a function which is declared inline and immediately executed. Again, the function will be executed, which is still probably what you care about.

Both of these will execute the same function, so there won't be any significant difference.

The difference between a snippet like yours and a simple function declaration:

The functions you've given are also identical to the following. I've just added a function name and assigned the return value for syntactical accuracy, which you can ignore for now.

// javascript...
var val =
function myFooFunc () {
alert("foo");
}();

However, this would be easily mistaken for a simple function declaration, which is different:

// javascript...
function myFooFunc () {
alert("foo");
}

Notice that the only real difference here is that this last function declaration is not executed immediately. The others are. So that is a very different behavior (the simple declaration may be executed later if it is called by name, or it may not ever execute at all). It's often hard to see that difference in the syntax right away, however, especially if the function body grows to be very long and requires scrolling on the screen.

Why are functions executed immediately?

When a function is immediately executed after it is declared, the value is often being returned to something (it may be part of an assignment statement). Sometimes the function is being executed right away because it contains inner functions and is being used to provide functional scope to the inclosed statements.

Essentially, people wrap parenthesis around the "executed immediately" form (both of your snippets, and the first one of my two) in order to give a visual cue to other developers that the function is being called immediately. It's just easier to read, since you might not catch the parenthesis until you got to the end of the function (or notice them at all).

When do I use parentheses and when do I not?

myFunction is a function

myFunction() calls the function and yields whatever value the function returns.

The purpose of setTimeout is running code after some time elapses. You need to pass just the function to it (so setTimeout can itself call the function when appropriate) because if you called the function (with the parenthesis) before passing it to setTimeout it would execute now instead of after 1 second.

Why in Javascript event handler functions with parentheses?

Inline JS

When you do an inline onclick handler like that, you're assigning a Javascript expression to run. So you need to execute the function.

The expression could just as easily be onclick="handler();alert(2)" in which case its obvious that the function needs to be called, just like it would be if it were run from a javascript file.

Binding a function to the click event

If instead you attach the click event with javascript, you would be binding a function, so you just need to pass the function object.

var btn = document.getElementById("btn");
btn.addEventListener("click",handler);

addEventListener sets the function object to be bound to the event so that it executes when the event is triggered. Since you're specifying a function object, rather than a string expression, the parentheses are not needed. In fact if you added them the function would execute immediatelly and the return value of the function would be bound to the event.

Best Practice

In general most people would advocate you bind events in javascript by binding a function handler rather than using inline JS. Its easier to debug, doesn't tightly bind your logic to the DOM, and is more flexible for dynamic pages. It also forces you to make any functions that you're calling global.

Summary

The key is the attribute points to a string that is evaluated as a JS expression, it is not the same as binding a function object to the event.



Related Topics



Leave a reply



Submit