Search code examples
javascriptnode.jsnode-modulesrequire

var module = require() or const {module} = require()?


Whats the diference between this two require methods:

1. var xx = require('module')
2. const {xx} = require('module')

I saw the first onde I can access xx as variable, with all script exported by module.. and second xx are undefined. How to access second "method" or is it a method too construct module to use {}

thanks


Solution

  • The first puts the full module handle in a variable named xx.

    The second gets the xx property from the module handle and puts it in a variable named xx. So, the second would be the same as:

    const xx = require('module').xx;
    

    Also the first is using var and the second is using const, but I assume you already knew about that difference.


    Said a different way:

    This:

    const {xx} = require('module');
    

    is a shortcut for this:

    const xx = require('module').xx;
    

    It's most useful as a shortcut when using require(), when you want to get a bunch of properties from the module and assign them all to top level variables in your module like this:

    const {xx, yy, zz, aa, bb, cc} = require('module');
    

    which would obviously take a lot more code to replicate than that single line if you weren't using the object destructuring syntax.

    FYI, all of this is just a form of object destructuring (a feature added to Javascript in ES6). It's not anything specific for require(), it's just that require() often returns an object with a bunch of properties that one is interested in. See this article "A Dead Simple into to Destructuring" for a nice summary of what object destructuring does.