I’ve spent hours trying to understand why this happens.
I’m trying to complete the Profile Lookup Challenge and I can satisfy all of the rules except for one. Which prioritizes the “No such contact” response over the “No such property” response when both parameters are not available.
I initially had the code to represent the "No such contact " response at the end of a loop, and it works but it does not satisfy the rules of the challenge, as it returns “No such property” in the event that both parameters are not available.
However when I try to reposition my the code that compares the name parameter to the for loop iteration, Whenever I use a prop parameter that is invalid, in the console.log() the == operator shows that the iteration is broken once the parameter entered is available and if I use the != operator it removes or skips the index of any valid parameter that’s entered from iteration.
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(name, prop) {
// Only change code below this line
for ( var i = 0; i < contacts.length; i++) {
var f = contacts[i].firstName; //used f variable to represent first loop variable j
var x;
var y = contacts[i].firstName; // used y variable to iterate second loop variable i
/*This initial IF statement always removes correct name property from iteration if != operator is used*/
if ( f != name) {
console.log(f)
}
//This console.log shows that this IF statement in the for loop iterates correctly and does not break
if (y == name && contacts[i].hasOwnProperty(prop)) {
console.log(f)
x = contacts[i][prop];
}
else if (contacts[i].hasOwnProperty(prop) == false) {
x = 'No such property';
}
}
return x;
// Only change code above this line
}
console.log(lookUpProfile("Akira", "cat"));
Browser Information
Google Chrome
Version 92.0.4515.107 (Official Build) (64-bit)
Challenge:
Profile Lookup
Link to the challenge: