Search code examples
javascriptoopobjectiterationfor-in-loop

Why doesn't object dot notation work in a for...in loop?


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);
}

Solution

  • 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