Using const with curly brackets

Viewed 168

I came across the following code:

const { userinfo } = userInfo;

I'm wondering, why do we use curly brackets with the const here?

1 Answers

In Javascript this syntax is called destructuring assignment and more specifically object destructing. Let's say you have an object:

const obj = { data: {...}, user: {...} }

For instance, when you write:

const { data, user } = obj
console.log(data)

Here you define new variables data and user and assign corresponding property values from the object obj to those variables.


It seems like in your case you have a local variable:

userInfo = {userInfo: {...} }
const { userinfo } = userInfo;

Deconstructing userInfo into { userInfo } would give you an error:

Uncaught SyntaxError: Identifier 'userInfo' has already been declared

Related