The Profile Lookup challenge using "&&" instead of nested ifs

Tell us what’s happening:

As you can see I’m using && instead of nested if statements. I don’t understand why it doesn’t work right!!! Is there any deference between using && or nested ifs?!

Your code so far


// 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){
for (var i = 0; i < contacts.length; i++) {
    if (contacts[i].firstName === name && contacts[i].hasOwnProperty(prop)){
        return contacts[i][prop];
    } else {
    return "No such property";
  }
}
return "No such contact";
}

lookUpProfile("Akira", "likes");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36.

Challenge: Profile Lookup

Link to the challenge:

when does the else statement execute?

2 Likes

when
contacts[i].firstName != name happened
or
contacts[i].hasOwnProperty(prop) becomes false
the else statement should execute.

I would run it through the debugger or use something like this code visualizer, see if you can’t figure it out by looking at the code execution.

Example:

lookUpProfile("Sherlock", "likes")

You loop the array, the first object is one where firstName is “Akira”, that doesn’t match “Sherlock” (name parameter), so you return out of the loop and function and never check the rest of the array.

1 Like

Exactly. See @lasjorg’s comment regarding what happens if the first contact in the array is not the name being passed.

1 Like