The goal of this code is to find cats with a “talkative” personality and create an array of their names — but the error code won’t do the trick.
Code with error
Corrected code
Explanation
cats.catName.personality
expects to find a key in the cats
object that matches the string "catName"
. In this case, there is no key "catName"
(only the keys "moxie"
and "gus"
). So cats.catName
evaluates to undefined
, and cats.catName.personality
results in a TypeError:
To access the value of catName
as the property, we need to use bracket notation : cats[catName].personality
.
Alternative solution
You could also solve this using Object.entries()
instead of Object.keys()
, but it’s a bit more involved:
Corrected code
Further Reading
- The MDN Property Accessors article discusses dot notation vs. bracket notation
- MDN Object.keys() , Object.values() and Object.entries()