Reputation: 113
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})
Upvotes: 1
Views: 346
Reputation: 370679
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 }
Upvotes: 4