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

11

It is common to see, in codes that use jQuery, references to selectors using $() . But I've already found codes using jQuery() to make selection queries .

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

    
asked by anonymous 10.04.2017 / 14:51

3 answers

11

jQuery serves both names.

There are several libraries that also use the ($) signatures as the name of some main function, which may conflict with jQuery. Calling jQuery by the jQuery () function makes explicit that you refer to this library and not the other as MooTools , for example. JQuery has mechanisms to avoid name conflicts in these cases, see Lucas Costa's answer.

In practice, you only have 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 this is probably not the case for most of us.

    
10.04.2017 / 15:00
7

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

See the jQuery.noConflict () reference

    
10.04.2017 / 14:55
7

Just completing the response from Lucas and the #, for clarity, 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 taken from the /src/exports/global.js file jQuery official repository.

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

window.jQuery = window.$ = jQuery;

Demonstrating Lucas's response, where% w / o% is defined as alias for $ . The code snippet prior to this line is intended to avoid conflict with other libraries - note the variables jQuery and _jQuery .

    
10.04.2017 / 15:02