I'm working through freecodecamp and am on the following excercise:
Now my code is as follows:
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
// Only change code below this line
for (var i = 0; i < contacts.length; i++) {
if (contacts[i].firstName == name) {
foundName += 1;
}
if (contacts[i].firstName == name && contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
} else if (contacts[i].firstName == name && contacts[i].hasOwnProperty(prop) == false) {
return "No such property";
}
}
if (foundName < 1) {
return "No such contact"
};
}
var foundName = 0;
// Only change code above this line
// Change these values to test your function
var ans = lookUpProfile("Bob", "number");
console.log(ans);
So I'm looping through the pre-defined array with my for loop and I'm checking for instances where name == firstName and where the object has a property of prop. In these instances I am returning the property. Otherwise, I return "No such Property". I'm also changing my variable foundName so that when firstName is matched to name in the loop, foundName gets a positive value. IF foundName is less than 1 (i.e. no name matches found) then I return 'No such contact'.
Now, when I run this in my browser and look in the console it seems to work perfectly. However, when I enter this answer into freecodecamp, I get:
"Bob", "number" should return "No such contact" "Bob", "potato" should return "No such contact"
But if I put, for example, "Bob" and "number" into the function, I do get "no such contact"... I must be missing something obvious here but I am extremely confused by this!!