We have an array of objects representing different people in our contacts lists. We have a lookUpProfile function that takes name as an argument. The function should check if name is an actual contact's firstName. It will print the contact name's on the console, followed by true if the name matches the contact's firstName, otherwise, it will print false.
I want my while loop to traverse the array until either nameCheck equals true OR i got bigger than contact length (aka it reaches the end of the array).
It seemed like both of the conditions in my while loop (nameCheck == false || i < contacts.length) are not working. For some reason even when namecheck equals true and i got bigger than contact length, the while loop keeps executing.
I know you can achieve the same result with a for loop instead and I had done that. But for the sake of learning, I would like to know why my while loop doesn't work.
Thank you so so much in advance.
const contacts = [
{
firstName: "Akira",
lastName: "Laine",
likes: ["Pizza", "Coding", "Brownie Points"],
},
{
firstName: "Harry",
lastName: "Potter",
likes: ["Hogwarts", "Magic", "Hagrid"],
},
{
firstName: "Sherlock",
lastName: "Holmes",
likes: ["Intriguing Cases", "Violin"],
},
];
function lookUpProfile(name) {
var nameCheck = false;
console.log(nameCheck);
var i= 0;
console.log (i);
while (nameCheck == false || i < contacts.length){
var nameOnContacts = contacts[i].firstName;
console.log(nameOnContacts);
nameCheck = nameOnContacts === name;
console.log(nameCheck);
i++;
console.log(i);
};
};
lookUpProfile("Akira");
What the console output:
›
false
›
0
›
Akira
›
true
›
1
›
Harry
›
false
›
2
›
Sherlock
›
false
›
3
›
TypeError: contacts[i] is undefined (/index.js:28)
/index.html