5/6 Building an Address Book


#1

I'm getting the error message - "TypeError: Cannot read property 'lastName' of undefined". I get it whether or not I have the "else" statement or not. Where is it coming from?

Code -

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++) {
printPerson(contacts[i]);
}
}

/*Create a search function
then call it passing "Jones"*/
function search (lastName){
var contactsLength = contacts.length;
for (var i = 0; i <= contactsLength; i++){
if (contacts[i].lastName === lastName){
printPerson(contacts[i]);
} else {
console.log("Name not found.");
}
}
};
search("Jones")


#2

Add a return command before this line, and it should work :wink:


#3

Inside a loop is not the place to announce it is not found. If the list is large and the match is found on the last iteration, there will be an endless stream of junk output.

The place for that message is after the loop is completed. For that you would need a flag, though, to tell it whether or not to display.

All you really need is a simple function with one purpose in mind... Print the matches.

function search(name){
    for (var i = 0; i < contacts.length; i++) {
        if (contacts[i].lastName === name) {
            printPerson(contacts[i]);
        }
    }
}

With a match found flag, it would look like this:

function search(name){
    var flag = true;
    for (var i = 0; i < contacts.length; i++) {
        if (contacts[i].lastName === name) {
            printPerson(contacts[i]);
            flag = false;
        }
    }
    if (flag) {
        console.log("Name not found.");
    }
}

#6

Is this just a case of the interpreter needing to see it there to continue? The code seemed to work without it is why I ask


#7

If you wish for your loop to run to completion of all the data, then you would not write return inside the loop. That is not good advice, and should be ignored, imho.