So I’ve recently begun learning Javascript using the tutorials on freecodecamp and there’s this challenge I’ve been stuck on for a few hours now.
The function always returns ‘No contact found’ and I don’t understand why. If someone were to explain it to me and correct my code, I’d be grateful.
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) { for (var i=0; contacts.length>i; i++) { if (contacts[i][firstName]==firstName) { if (contacts.i.prop.hasOwnProperty()===true) { return contacts.i.prop; } else { return "No such property"; } } return "No such contact"; } } lookUpProfile("Akira", "lastName");
Advertisement
Answer
Try this
Explanation
Typo error change like this
contacts[i]['firstName']
instead ofcontacts[i][firstName]
.you are missing to match thekeyname
ofobj
.for your way its calling likecontacts[i][Akira] == false statement
so only it always go else statementDo the object key call method with
obj[key]
instead ofobj.key
.Beacuse all are varible not with direct name of the keysecond one
hasownproperty(varible)
.you are not mention which word to check with that object
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) { for (var i=0; contacts.length>i; i++) { if (contacts[i]['firstName']==firstName) { if (contacts[i].hasOwnProperty(prop) === true) { return contacts[i][prop]; } else { return "No such property"; } } return "No such contact"; } } console.log(lookUpProfile("Akira", "lastName"));