1

for example, I have an object but when i send this object key inside curly brackets it gives error.

const user = {name: "fishLegs"}
userModerl.create({user.name})

while taking that key inside another variable makes it work fine. Why so?

const user = {name: "fishLegs"}
let userName = user.name
userModerl.create({userName}) 

1 Answer 1

4

In JavaScript, objects are key-value pairs.

Normally, if you try to list a plain expression (a value) inside an object literal, the syntax will not be valid, because you need both a value and a key. That's why {user.name} fails.

There's an exception, though: if you have a standalone variable (not something that's a property of an object, it needs to be a standalone identifer), listing just that identifier creates a property on the object with the same name as the variable, with a value of what's contained in the variable.

{ someVar }

is equivalent to

{ someVar: someVar }

but such a thing can't be done (and doesn't really make sense) for

{ user.name }
Sign up to request clarification or add additional context in comments.

3 Comments

There’s a proposal to make this syntax possible.
so i can write userModel.create({name : user.name}).. makes sense now
i thought it would automatically take that key of the first object and make its own key with same name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.