+ 1

Undefined

Why does this code show undefined when I run it? const user = { name: 'George', age: 31, } let key = 'name'; console.log (user.key);

5th Dec 2021, 10:12 PM
IKECHUKWU, GAVIN C
IKECHUKWU, GAVIN C - avatar
4 odpowiedzi
+ 6
You can do user[key] or user.name
5th Dec 2021, 10:30 PM
Lisa
Lisa - avatar
+ 3
console.log (user.name); or console.log (key); or console.log (user['name']); Good Luck :)
5th Dec 2021, 10:27 PM
SoloProg
SoloProg - avatar
+ 3
Because user has just two properties (name and age), not key. The value of key is a property of user.
5th Dec 2021, 10:46 PM
Mafdi
Mafdi - avatar
+ 1
user[key] https://code.sololearn.com/W37hGD6IyXQc/?ref=app [ ] is used when we don't know the property name in advance. Reference: Morpheus JS Fact Series #57: the post: https://www.sololearn.com/post/46592/?ref=app his example code: https://code.sololearn.com/WT1rPvuw28y2/?ref=app
6th Dec 2021, 9:39 AM
Gordon
Gordon - avatar