Josh Christensen Josh Christensen - 1 month ago 10
Javascript Question

Differences between $(document).ready(function(){ functionName() }) and $(document).ready(functionName())

I was asked a question that I don't have a good answer for lol

I'm curious, is there any difference between the 2?

Is one just passing a function inside an anonymous function when "ready" whereas the other is passing an actual named function when "ready"?

Example:

<p>Not loaded yet.</p>


First:

function newName() {
$( "p" ).text("The DOM is now loaded and can be manipulated.")
}

$(document).ready(function() {
newName()
});


Second:

function newName() {
$( "p" ).text( "The DOM is now loaded and can be manipulated.")
}

$(document).ready(newName());


Is one more correct than the other?

Answer

Is one just passing a function inside an anonymous function when "ready" whereas the other is passing an actual named function when "ready"?

Yes and no.

I'm curious, is there any difference between the 2?

The first is passing an callback function that is executed when the event fires. When that even fires is explained here.

The latter passes the resolved return value (which is undefined because newName has no return statement), which isn't the same as the second. The reason it passes the return value to ready is because you invoke the function immediately (which may seem like it works), which then passes the return value. To make them functionally equivalent, do:

$(document).ready(newName);

This will pass a function reference, and won't invoke it.

As mentioned before, invoking as ready(func(); func2();) is not valid syntax.