I am trying to figure out why console prints undefined
when I use dot notation
when why it prints values of each key when I use bracket notation
.
What I want is to print the values of each key, so I use bracket notation. I just want to know why dot notation doesn't work.
Below is the example.
const sunny = { mac: 'priest', dennis: 'calculating', charlie: 'birdlaw', dee: 'bird', frank: 'warthog' };
for(var key in sunny){
console.log(sunny.key)
}
for(var key in sunny){
console.log(sunny[key])
}
undefined
undefined
undefined
undefined
undefined
"priest"
"calculating"
"birdlaw"
"bird"
"warthog"
for(var key in sunny){
console.log(sunny.key)
}
sunny.key in bracket notation is equivalent to sunny["key"]. It is searching for a property name "key" which is not there in your object.Hence returning undefined always.
key here is actually variable , not a string to extract the value of a property.
See : https://codeburst.io/javascript-quickie-dot-notation-vs-bracket-notation-333641c0f781