Object is undefined, though I define it

I am befuddled as to why I’m receiving the undefined value pertaining to variables and objects below.

let nameObj = { last: "Capulet" };
console.log(Object.keys(nameObj)) // prints 'last'

let key = Object.keys(nameObj);
console.log(key) // prints 'last'

console.log(nameObj.key); // prints undefined

Can someone explain where the logical mishap is? I expected the console to print ‘Capulet’

Thank you

Your object is not undefined, nameObj.key is undefined because it has not property called “key”. There is another error in that you think Object.keys in that you think it returns a string - it doesn’t - it returns an array of strings.

I think this might be what you’re looking for:

let nameObj = { last: "Capulet" };
console.log(Object.keys(nameObj));

let keys = Object.keys(nameObj);
console.log(keys);

let key = keys[0];
console.log(key);

console.log(nameObj[key]); 

You may want to revisit the following lessons:


Also, it doesn’t log last, it logs ["last"]. There is a big difference.

Thanks for explaining that. I didn’t realize that because my object only has one key! Now I see the error.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.