1

Running some tests through Chai, I noticed the tests would fail under this code:

const add = require('./addition');
//'add is not a function error' even though it's directly exported as a function

But it would pass under this:

const {add} = require('./addition');

Yet when using npm modules, everything is declared without the brackets:

var express = require('express');
var app = express();
var session = require('express-session');

And those are essentially objects with multiple properties to be accessed. Why does it work this way? Is it only function exports that must be assigned as objects explicitly?

Arcaster
  • 119
  • 8
  • 1
    You have some explication [here](https://stackoverflow.com/questions/38660022/curly-brackets-braces-in-node-require-statement) – Hadock Jun 21 '19 at 11:18

1 Answers1

5

This is known as object destructuring. Please refer the link.

For example you have exported a file called sampleFunctions.js which has following functions as exports

function function1(params) {};
function function2(params) {};

module.exports = {
sampleFunc1: function1,
sampleFunc2: function2
}

Now when you need to require it, there are two ways -

  • when you only need one function(using object destructuring)
let {sampleFunc1} = require('./sampleFunctions');
sampleFunc1();

In this you exposed only the required function not all of the functions exported from that file.

  • when you want to require all the functions from that file
let sampleFuncs = require('./sampleFunctions');
let samFunc1 = sampleFuncs.sampleFunc1;
samFunc1()
Siddharth Yadav
  • 383
  • 2
  • 9