1
car = { 
 color: 'green',
 speed: '340',
 drive: function() {
  alert("brrrrrrm");
 } 
}

This works:

for(elem in car) {
  console.log(car[elem]);
}

But this doesn't work, returns undefined for every element:

for(elem in car) {
  console.log(car.elem);
}
4
  • 4
    Do you have any key named "elem"? No. That's why. Commented Aug 13, 2016 at 14:28
  • 1
    @GerardoFurtado damn that was fast and accurate, thanks! Commented Aug 13, 2016 at 14:29
  • This answer might give some insights.
    – Tholle
    Commented Aug 13, 2016 at 14:33
  • The "brrrrrm" part made me smile. :)
    – brat
    Commented Oct 3, 2020 at 15:56

1 Answer 1

3

When you write car.elem, you're trying to access the elem property of car object, which does not exist.

But when you use car[elem], you're trying to access the property of car object that has the name the same as that stored in the variable elem.

Hence, if you use the "dot notation" you'll end up calling the elem property of the car object.

car = { 
 color: 'green',
 speed: '340',
 elem: 'This is the elem property of car object',
 drive: function() {
  alert("brrrrrrm");
 } 
}

Accessing properties:

for(elem in car) {
  console.log(car[elem]);
}

Console Output:

green
340
This is the elem property of car object
function () {
  alert("brrrrrrm");
}

Then we do:

for(elem in car) {
  console.log(car.elem);
}

Console Output:

This is the elem property of car object
This is the elem property of car object
This is the elem property of car object
This is the elem property of car object

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.