JosephByrne
JosephByrne

Reputation: 123

Why does this function print out 'undefined'?

The list function below is supposed to list the names of the people in my contacts array.

var bob = {
    firstName: "Bob",
    lastName: "Jones",
    phoneNumber: "(650) 777-7777",
    email: "[email protected]"
};

var mary = {
    firstName: "Mary",
    lastName: "Johnson",
    phoneNumber: "(650) 888-8888",
    email: "[email protected]"
};

var contacts = [bob, mary];

function printPerson(person) {
    console.log(person.firstName + " " + person.lastName);
}

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

list;

However, instead of just printing out Bob Jones and Mary Johnson, I get:

Bob Jones
undefined
Mary Johnson
undefined

Can someone explain why this is?

Upvotes: 1

Views: 193

Answers (3)

Akinkunle Allen
Akinkunle Allen

Reputation: 1309

Your printPerson function writes to the console. It does not return a value explicitly. When a function without an explicit return value runs, it returns the undefined value. The console always tries to display the return value of a function after it runs, if an explicit value is not set, it returns the value undefined.

Upvotes: 0

DACrosby
DACrosby

Reputation: 11430

Try this:

function printPerson(person) {
    return person.firstName + " " + person.lastName;
}

Upvotes: 0

p.s.w.g
p.s.w.g

Reputation: 148980

Your printPerson method writes to the console, but does not return any value, so in your for-loop where you have:

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

It's also trying to write the return value of printPerson to the console, which is undefined.

To fix this, either drop the console.log from the for-loop or return a value from printPerson rather than writing to the console there.

Upvotes: 5

Related Questions