NodeJS [SOLVED]: what does require('jquery') return and why multiple assignments

NodeJS [SOLVED]: what does require('jquery') return and why multiple assignments

Home Forums Scripting NodeJS Tutorials NodeJS [SOLVED]: what does require('jquery') return and why multiple assignments

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #245808

    Cloudy Point
    Keymaster

    QuestionQuestion

    I am new to nodejs and javascript and I tried to get an answer for this question but after investing plenty of time, I couldn’t find an answer on the internet.
    I now know what require and export are doing. I am analyzing some code and it has the following code line:

    var $ = global.jQuery = window.$ = require('jquery');
    

    So here as I have understood the export object of 'jquery' is returned. As I have read from this thread, the code is equal to:

    var $ = (global.jQuery = (window.$ = require('jquery')));
    

    I hope that this is correct. If not, what is the code meaning? Then my question is, what is now var $ containing?

    #245809

    Cloudy Point
    Keymaster

    Accepted AnswerAnswer

    what does require('jquery') return

    require('jquery') returns a new jquery object, exported by modules.export as you’re already familiar with. As any Node module, you can assign this to whatever you like.

    Don’t be confused by the $, it’s a valid variable name in JavaScript.

    why multiple assignments

    Syntactical, one-liner convenience, that’s all.

    • window.$ is for compatibility with running in the browser
    • global.jQuery is two fold.
      • Having jQuery available is a great fallback for when $ is unavailable such as when running multiple versions of jQuery. I’ve found this to be fairly common in large projects due to compatibility differences with some 3rd party projects.
      • Since variables are usually locally scoped in Node by default, global has additional, reserved meaning to make the jQuery object available to other portions of code without require()ing it again.
    • $ is the most common usage in the API examples, so it’s there for comfort, not necessity.

    Source: https://stackoverflow.com/questions/47995083/what-does-requirejquery-return-and-why-multiple-assignments
    Author: QZ Support
    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.