Difference between '$()' and 'jQuery()'

Asked

Viewed 425 times

12

It is common to see, in codes that use jQuery, references to selectors using the $(). Only I’ve already found codes using jQuery() to make darlings selection.

What is the difference between them? Can I use either or have specific cases for each one’s use?

3 answers

11


jQuery goes by both names.

There are several libraries that also use the dollar sign ($) as a name of some main function, which may conflict with jQuery. Calling jQuery by the jQuery() function makes it explicit that you refer to that library and not to another one as MooTools, for example. jQuery has mechanisms to avoid name conflicts in these cases, see Lucas Costa’s response.

In practice, you only need to worry about this when you have to work with some library that also uses the dollar sign. This is part of the day-to-day lives of many developers, but is likely not to be the case for most of us.

7

$() is an alias for jQuery(). Many javascript libraries use $ as function or variable names just like jQuery does.

See the reference of jQuery.noConflict()

7

Just completing the answer from Lucas and of Renan, to be clearer, just check the source code of the library:

define( [
    "../core"
], function( jQuery, noGlobal ) {

"use strict";

var

    // Map over jQuery in case of overwrite
    _jQuery = window.jQuery,

    // Map over the $ in case of overwrite
    _$ = window.$;

jQuery.noConflict = function( deep ) {
    if ( window.$ === jQuery ) {
        window.$ = _$;
    }

    if ( deep && window.jQuery === jQuery ) {
        window.jQuery = _jQuery;
    }

    return jQuery;
};

// Expose jQuery and $ identifiers, even in AMD
// (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if ( !noGlobal ) {
    window.jQuery = window.$ = jQuery;
}

} );

Code snippet from archive /src/exports/global.js from the official jQuery repository.

This file implements the logic of exporting variables to the global context. In most cases, for simple applications, the code snippet that will prevail will be:

window.jQuery = window.$ = jQuery;

Demonstrating Lucas' response that $ is defined as alias for jQuery. The code snippet before this line aims to avoid conflict with other libraries - note the variables _jQuery and _$.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.