I dont understand the solution

// Setup
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++) {
    if(contacts[i].firstName === name) {
        if (contacts[i].hasOwnProperty(prop)) {
        return contacts[i][prop];
        }
        else {
            return "No such property"
        }
}
}
return "No such contact"
// Only change code above this line
}
lookUpProfile("Akira", "likes");

Please help me understand why the second if statement was nested inside the first one. Also, shouldn’t shouldn’t the string “No such contact” be returned by an else if statement ?

PLEASE HELP!

1 Like

@mashudumatoti, see if you can understand this way:

step 1:

for(var i = 0;  i < contacts.length;  i++){
if(contacts[i].firstName===name){
// if the name found in the contact list we will use this

} else{
       return " No such contact" // since no contact matched
    }
}
 

step 2: what do we want if a name matched

for(var i=0; i<contacts.length; i++){
if(contacts[i].firstName===name){
/* think if we look for Akira, it will be matched, then what do we want
// we again want to check if Akira has any own choice, here (likes property)
// lets see this in code*/

if(contacts[i].hasOwnProperty(prop)){
// if we find Akira has own likes we'll use this
// for this case, for Akira has own likes as you see in the contacts
// now decide what we need as condition matched
// well, we need to know how many things Akira likes, call it now

return contacts[i][prop]

}else{
// if Akira has no likes 
return "No such property"
}




} else{
       return " No such contact" // since no contact matched
    }
}

step 3: now we are calling the main function with name (here Akira) and prop (here likes) as shown in your code

lookUpProfile("Akira", "likes");

you can check the output in the console

console.log( lookUpProfile("Akira", "likes") )

Hope this will help you.

Thank you.

1 Like

Hey there, sorry for taking forever to respond. I’m kinda bad with replies.
This makes a lot of sense thank you for taking the time to explain it to me, I really appreciate it

1 Like