1

printPerson takes an object as an argument, its loop iterates trough all its properties and is suposed to print them all out.

As you can see I've logged both the person and property variables and they are working fine. person is identified as an object, and property as a string with the correct property name, indicating that the loop is also working fine. But when it comes to logging person.property, the return value is undefined.

What am I missing?

var bob = {
    firstName: "Bob",
    lastName: "Jones",
    phoneNumber: "(650) 777-7777",
    email: "bob.jones@example.com"
};

var mary = {
    firstName: "Mary",
    lastName: "Johnson",
    phoneNumber: "(650) 888-8888",
    email: "mary.johnson@example.com"
};

var contacts = [bob, mary];

function printPerson(person) {
    for (property in person){
      console.log(person);
      console.log(property);
      console.log(person.property);
    }
}

function list(){
    for (var i=0;i<contacts.length;i++){
        printPerson(contacts[i]);
    }
}

list();
Scb
  • 339
  • 1
  • 5
  • 19

1 Answers1

3

You need to use bracket notation when using variables as keys:

console.log(person[property]);

Here are the relevant docs: MDN on Objects Properties

omarjmh
  • 13,632
  • 6
  • 34
  • 42