Home > Blockchain >  What is the difference between require with curly braces and require normal?
What is the difference between require with curly braces and require normal?

Time:11-11

What is the difference between this

const authController = require("../controller/authController");

and this

const { authController } = require("../controller/authController");

my code doesnt work when i call a function like authController.createUser in second one and i wondered thats why?

Thanks for helps.

CodePudding user response:

The difference between example one and example two is that you are using the Destructuring Assignment method in example two. That means, you can destruct an Object, or Array to have the keys of the object as variables.

So, for example if we take this simple object and we start destructuring:

const someObject = {
    something1: "1",
    something2: "2",
    something3: "3",
    something4: "4",

};

const { something1 } = someObject;
console.log(something1) // Returns 1

You see that we can use something1 as a "new variable" instead of accessing it by using someObject.something1.

In your case you are including a module / class with the name authController, but if your module doesn't have a method or key called authController, using the following method:

const { AuthController } = ...

won't work, because it's unable to access this method or key.

So, the first one: authController.createUser() will work because you are loading up the entire module without destructuring the module. If you do something like this const { createUser } = require("authController"), you can use it like createUser(...)

CodePudding user response:

Difference between

const authController = require("../controller/authController"); 

and

const { authController } = require("../controller/authController");

is, when your module exported by default from your .js file we use first syntax, while if there are several modules getting exported from a single .js file we use the second syntax. Also you cannot have more than one default export from a file. Hope that helps.

  • Related