Hello everyone.
I’ve been doing fcc courses when I arrived at the lasts JS challenges.
The point is to write a simple function that will go trough a contact list to find a property based via the first name of that contact.
The contact list is stored in an object. Here’s what the code looks like when I started :
//Setup
var contacts = [
{
"firstName": "Akira",
"lastName": "Laine",
"number": "0543236543",
"likes": ["Pizza", "Coding", "Brownie Points"]
},
{
"firstName": "Harry",
"lastName": "Potter",
"number": "0994372684",
"likes": ["Hogwarts", "Magic", "Hagrid"]
},
{
"firstName": "Sherlock",
"lastName": "Holmes",
"number": "0487345643",
"likes": ["Intriguing Cases", "Violin"]
},
{
"firstName": "Kristian",
"lastName": "Vos",
"number": "unknown",
"likes": ["Javascript", "Gaming", "Foxes"]
}
];
function lookUpProfile(firstName,prop){
// Only change code below this line
// Only change code above this line
}
// Change these values to test your function
lookUpProfile("Sherlock","number");
I tried to use a while function that would go trough the contact list and stop as soon as it find a match between the argument “firstName” and the first name of one of the contact. Here’s what my code looks like :
var i = 0;
while (contacts[i].firstName != firstName|| i>=contacts.length){
i++;
}
return contacts[i][prop];
It’s all working so far, and everything work, but I stumbled upon a mistake that, it seems, comes from nowhere :
If I type a name that’s not on the contact list, such as ‘lookUpProfile(“Bob”,“number”);’ the console will display “Type Error : Cannot read property ‘firstName’ of undefined”. However, if I’m not mistaken, since I told the code to stop looking if " i " exeeds the array length, it should normally stop at 3 and simply return the property of the 4th contact, regardless of the name I type in the function.
I really do not understand what I did wrong, I know that I do not need to solve this for succeeding in the challenge, but it really bugs me and I can’t go forward before figuring where the hell this error comes from, since I tought I put a correct barrier to overlooping the contact’s array length.
Thanks a bunch to those who had the courage to read the whole thing. See ya !
edit : well, it was just a stupid mistake of mine, sorry !