I’m on this challenge: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/profile-lookup .
Here’s my code for the function:
function lookUpProfile(name, prop){
// Only change code below this line
for (let i = 0; i < contacts.length; i++) {
if (name === contacts[i]["firstName"]) {
if (contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
} else {
return "No such property";
}
} else {
return "No such contact";
}
}
// Only change code above this line
}
Out of the six tests, the first three fail and last three pass. But when I do
console.log(lookUpProfile("Akira", "likes");
or
console.log(lookUpProfile("Akira", "firstName");
or
console.log(lookUpProfile("Akira", "lastName");
I get the expected output. So what am I doing wrong and how do I fix it?
Thanks in advance.
I looked in hint for this challenge and your answer seems to be much different than the two supplied. You can find hints and the answer to your problem by pressing the “Get Help” button in your challenge and then pressing hint. I don’t want to directly give you the answer.
You’re using a for loop to go through each element in the contacts array. This is good, however, the way you’ve written the code inside the for loop, it is guaranteed to return at the first iteration. Here’s the logic inside the for loop:
If the firstName
of the contact at index i
is name
:
- then: if the contact at index
i
has the property prop
:
- then: exit the function and return the value of
contacts[i][prop]
- else: exit the function and return “No such property”
- else: exit the function and return “No such contact”
You don’t want to return “No such contact” until you have checked every single item in the contacts array and none of them have the correct firstName. In other words, you don’t want to return “No such contact” until the for loop is finished.
So it’d be better to store the return value in a variable and return it at the end of the function?
I just tried this:
function lookUpProfile(name, prop){
// Only change code below this line
for (let i = 0; i < contacts.length; i++) {
if (name === contacts[i]["firstName"]) {
if (contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
} else {
return "No such property";
}
}
}
return "No such contact";
// Only change code above this line
}
And that did it.
Thanks for the help, guys.