Node.js- question about some way to declare variable

line 1:
const {assert} = require(‘chai’);
what is this way of using the ‘{}’ to declare variable??

It’s called object destructuring.

If I have an object,

const me = { name: Taylor }

I can access my name by using // This would return "Taylor" if I accessed it

or I can create a variable and access it that way:

const { myName } = me
myName // would return "Taylor" as well

This quick example might seem silly, but what if I have an object with a lot more properties on it?

const me = {
   name: "Taylor",
   likes: "food",
   hates: "vodka",
   height: "6ft"

I could try accessing each property like, me.likes, etc… Or I could, in one line, make myself some handy-dandy variables I could use later when needed.

const { myName, myLikes, myHates, myHeight } = me

In the example you gave, it’s being used because the Chai testing library has MANY variables and functions, but we only want one, and we don’t want to have to type chai.assert every time. We’d rather type just “assert”, so we destructure that out of the library and we’re good to go.

1 Like

Thank you very much for the detailed explanation! I understood everything now

if it was in regular declaration so:
const assert= require(‘chai.assert’)'?

I believe that would technically work, yes.

1 Like