0

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"

user3646717
  • 1,095
  • 2
  • 12
  • 21
  • See also [this question](http://stackoverflow.com/questions/3246928/in-javascript-does-it-make-a-difference-if-i-call-a-function-with-parentheses). – nnnnnn Oct 06 '16 at 03:02

1 Answers1

3

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.

nbrooks
  • 18,126
  • 5
  • 54
  • 66
  • fwiw, `$(document).ready(undefined)` is not an error – Mulan Oct 06 '16 at 03:04
  • @nbrooks Correct. You can also test this in the console by writing the function `function test(){ alert("pen pineapple apple pen"); }` then call the function `test()` you will get the pop up but if you call the function without the parenthesis it will return the expression – Sergio Alen Oct 06 '16 at 03:06
  • @naomik - It's not a syntax error, nor does jQuery mind, but it is likely a mistake by the programmer. – nnnnnn Oct 06 '16 at 03:06
  • @naomik Sorry if I wasn't clear—if the developer included parentheses when they didn't intend to do so then it would be a programming error/mistake. That's all I meant to imply. – nbrooks Oct 06 '16 at 03:06
  • Thank you. So if the function is written with parentheses it executes immediately and the return value of that function is used by the ready function. But if I write just the name of the function, the reference to that function is passed to ready function to be executed when the document is ready. – user3646717 Oct 06 '16 at 03:18
  • @user3646717 Yep, exactly. – nbrooks Oct 06 '16 at 03:19