gBasgaard gBasgaard - 1 month ago 8
Javascript Question

How do I loop through an array with multiple objects and list certain elements in solely Javascript?

This is the code I have written. I want the

listContacts
function to loop through the
contacts
array and log the first and last name of each contact to the console. When I run this though it only logs John Doe to the console. What am I missing here?

var contacts = [
{
firstName : 'John',
lastName : 'Doe',
phone : '(512) 355-0453',
email : 'johndoe@email.com'
},
{
firstName : 'Jane',
lastName : 'Doe',
phone : '(313) 641-2203',
email : 'janedoe@email.com'
},
{
firstName : 'Suzie',
lastName : 'Smith',
phone : '(415) 604-4219',
email : 'suziesmith@email.com'
}
];

var listContacts = function () {
for (var i = 0; i <= contacts.length; i++) {
return contacts[i].firstName + ' ' + contacts[i].lastName;
}
};

console.log(listContacts());

Answer

Your return statement in your for loop is causing that loop to stop after the first iteration. Instead, you should log within the loop:

var listContacts = function () {
    for (var i = 0; i <= contacts.length; i++) {
        console.log(contacts[i].firstName + ' ' + contacts[i].lastName);
    }
}

listContacts();