4/6 'Undefined' Returned


#1

Results from the code below are printed in the console as:

Undefined Undefined
Undefined Undefined

Not receiving the names as desired but code is being accepted. Can anyone explain?

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) {
console.log(person.firstName + " " + person.lastName);
}

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

list();


#2

Try this one:

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

#3

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) {
console.log(person.firstName + " " + person.lastName);
}
function list(){

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

};
list();

i got the same results with out defining new variable { var contactsLength = contacts.length; }


#4

my works

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) {
console.log(person.firstName + " " + person.lastName);
}

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


#5

This one worked in my other js editor, http://fiddlesalad.com/javascript/ and returned the results just once.

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) {
console.log(person.firstName + " " + person.lastName);
}

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

list();

I don't get why we would need to define, var contactsLength = contacts.length. Why not just the following?

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