jQuery newbie: what does jQuery(function($) { ... }) means? jQuery newbie: what does jQuery(function($) { ... }) means? jquery jquery

jQuery newbie: what does jQuery(function($) { ... }) means?


jQuery(function($) {});

is the safest version of all three. It makes $ the local variable and thus gracefully avoids the conflicts with any other variables which possibly use $ symbol.

I think it was also added fairly recently, don't remember seeing it before.

These function all do the same things - execute some code when DOM is ready. $(document).ready(function(){}) is the original one, and it matches the underlying javascript API.

"$" and "jQuery" which accept function as an arguments were created as shortcuts to avoid repeating such a common construct. Accepting a function which accepts $ as its first argument is a further syntax sugar - now you get convenience of the closures without the need to do it yourself.


  • $(function()) is a syntax error.
  • $() creates an empty jQuery object.
  • $(document).ready(function() { ... }) executes the given function when the DOM is ready
  • $(function() { ... }) is a shortcut for the same thing
  • jQuery(function($) { ... }) does so, too, but it also makes $ available inside the function no matter what it's set to outside.


When you call the main jQuery factory function (either as jQuery(<something>) or the common shortcut $(<something>)) it decides what to do based on the type of <something>.

If you pass a string as <something> it assumes that is a selector specification and will return a jQuery list of elements matching that selector.

If you pass a jQuery object (representing a list of elements, i.e. an object returned from a previous call to jQuery) it will just return that object (essentially this is a non-operation).

If you pass it a DOM element it will return a jQuery list containing just that element (so you can apply jQuery methods to that element). This is what is happening with $(document).ready() - you pass the factory function the DOM element "document", it returns a jQuery object representing that element, and you use that object's ready() method to add an event handling function to the ready event of all the DOM elements in the list (just the one, document, in this case).

If you pass it a function, this is just a shorthand for "run this when everything is ready for you to do so", so $(function() { ... }); is equivalent to $(document).ready(function() { ... });