Samuel Fullman
Samuel Fullman

Reputation: 1312

jQuery difference in function call $(function(){})

I am posting this as I study deeper into both JavaScript and jQuery. The following code

$(function () { 
    alert('instance');
});

$(alert('hi'));

alerts "hi" and "instance" in that order! I'm sure there is an understanding into how js thinks on this because I would think it would be "instance" and "hi" - can anyone explain this? Thanks

Upvotes: 0

Views: 66

Answers (3)

John Dvorak
John Dvorak

Reputation: 27277

When you do

$(function () { 
    alert('instance');
});

, a function is created that will alert "instance", then the function is passed to jQuery ($). JQuery remembers the function, and calls the function when the DOM tree is loaded. This is an alias for $(document).ready(function(){...}).

When you do

$(alert('hi'));

alert('hi') is called immediately, and the return value will be passed to jQuery. Chances are "immediately" occurs before "when the DOM tree is loaded".

Everywhere I've tested, alert returns undefined. Passing undefined to jQuery has no observable effect as far as I can tell.

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

$(function(){}) is a shortcut for $(document).ready(function(){}) which means the execution of code inside $(function(){}) will be delayed till the document is completely loaded.

The code execution sequence here will be something like

  1. $(function(){}) gets executed resulting in registering a document ready callback
  2. $(alert('hi')); gets executed, here alert('hi') gets executed resulting in the popup and it returns a undefined value to jQuery which will ignore it.
  3. the document ready event is fired resulting the execution of the registered callback ie alert with instance

The difference between the code is in the first case you are not immediatly executing the function, you are passing the function as a parameter to jQuery (because there is no () after the function definition). In the second case you are calling alert('hi') which will result in calling the alert immediately and then passing the returned value of alert to jQuery

Upvotes: 0

anthony sottile
anthony sottile

Reputation: 69844

$(function() { ... }) is an alias for $(document).ready(function() { ... })

Your second is sort of nonsensical and evaluates something like this:

alert 'hi', then create a jquery object of the return value (I believe undefined)

Upvotes: 2

Related Questions