Josh Christensen Josh Christensen - 1 month ago 7
Javascript Question

Difference between passing a callback versus a function

I'm curious, is there any difference between the two functions below?

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 method:

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

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


Second method:

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 two?

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. Also, as mentioned before, invoking as ready(func(); func2();) is not valid syntax.