Basic JavaScript: Profile Lookup - Attempt

Hello. I am having trouble understanding why this code does not work. The code I am using is written exactly as the solution given on this forum, except that instead of nesting two ‘if’ statements to meet the first criteria required, I used the logical ‘&&’ operator.


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";
}

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

The problem with combining the two if statements is that now you will return “No such property” when a contact does not have a firstName that matches name. You will only ever check the first item in contacts because you either return the property value or you return “No such property”.

This makes sense! Thank you!

I’m glad I could help. Happy coding!

1 Like