5. Finding that Special Someone (PLEASE HELP!)


#1

I've been working on this for far too long, and I've looked through all of the other forum posts to try to find a solution. Could someone please tell me why I keep getting this error:

Oops, try again. You have the following error in your code: TypeError: Cannot read property 'lastName' of undefined

Here is my code for this section:

/*Create a search function
then call it passing "Jones"*/
var search = function(lastName) {
var contactsLength2 = contacts.length;

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

};

search("Jones");

PLEASE HELP!


#2

In your if you should have if(contacts[i]["lastName"] === lastName), and you're using =. That is the your mistake, because you will set your lastName to contacts[i["lastName"] every time, and that really makes no sense. That way you will set everybody's last name to "Jones", which is wrong. Fix = into === and your code should work (at least the part seen here).


#3

I've tried that before and it's given me the same errors. Any other ideas?


#4

Can you show the other part of your code? Maybe you made mistake somewhere earlier.And no matter what, you should use === because that will compare 2 things, and = will asign one to another.


#5

Here's the full code. Hopefully you can find something I can't.

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"*/
var search = function(lastName) {
var contactsLength2 = contacts.length;

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

};

search("Jones");


#6

Ok I think I've got it. Can't believe I didn't see it before.
You have 2 items in your contacts array. When you run for loop, you set an end at i <= contacts.length, which is wrong.
You see, your for loop will run once for index 0, 2nd time for index 1 and third time for index 2. But there is no index 2. contacts[2] is not defined, that's why you're getting TypeError: Cannot read property 'lastName' of undefined.

Just change end conditions in for loop from <= to < and your code should work, other things seems fine.


#7

Brilliant! I can't believe I missed that! It just worked. Thank you so much for all your help!