user3646717 user3646717 - 1 month ago 11
Javascript Question

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

Well I'm starting with jQuery and I'm wondering what is the difference between writing a function with or without parentheses inside a function.
For example if I have the following function:

function test(){
alert("pen pineapple apple pen");
}


This:

$(document).ready(test);


and this:

$(document).ready(test());


both show the same result: "pen pineapple apple pen"

Answer

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.

Comments