ethikz
ethikz

Reputation: 379

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?

Upvotes: 0

Views: 98

Answers (2)

Andrew Li
Andrew Li

Reputation: 57982

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.

Upvotes: 2

Sebastian Simon
Sebastian Simon

Reputation: 19535

Effectively there’s no difference between

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

and

$(document).ready(newName);

There’s a small technical difference: in the first snippet, an anonymous function calling newName is passed, in the second snippet, the named function newName itself is passed.

Functions are just callable objects that can be referenced by their name or the name of a variable holding the function.

Note that $(document).ready(newName()); is calling newName — immediately — and passing the return value to ready. This only makes sense if newName returns another function, which in this case it doesn’t.

The title also mentions something like $(document).ready(newName){}. I’m assuming that’s a typo, since that’s not valid syntax.

$(document).ready(newName(); otherName(); otherName1()); also isn’t valid syntax.

Upvotes: 1

Related Questions