Search code examples
javascriptjqueryclientscript

Why we have to use $.noConflict() in jQuery?


I know we are using $.noConflict() to overcome other plugin conflicts. For example, if some new plugin use the $ symbol as a variable it will override. so, we are using like below

var $j=$.noConflict();

But, i am having doubt here, We can archive this using below code itself then why $.noConflict(); needed?

 var $j=$;

Thanks advance. Kindly explain major different


Solution

  • Here you got detailed information about why:

    Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $. If you need to use another JavaScript library alongside jQuery, return control of $ back to the other library with a call to $.noConflict(). Old references of $ are saved during jQuery initialization; noConflict() simply restores them.

    It's from jQuery and there is even more information: https://api.jquery.com/jquery.noconflict/

    Update after comment

    From jQuery code https://code.jquery.com/jquery-1.10.2.js if you search for noConflict you will find

    noConflict: function( deep ) {
            if ( window.$ === jQuery ) {
                window.$ = _$;
            }
    
            if ( deep && window.jQuery === jQuery ) {
                window.jQuery = _jQuery;
            }
    
            return jQuery;
        },
    

    In simple: This checks if global $ or global jQuery has already been used. Either way it will return jQuery. So you can not just do var $j=$; cause $ may already has conflicts. The noConflict() is what you need.