Profile Lookup - Not understanding logic

Can someone please help me understand what it is that I am missing in my logic here? I found answers to this problem that use logic to make it shorter, but I am just trying to understand how to put it together properly if I just go down the list of things to do and write the code. Without making it more complicated by putting step 3 first and stuff like that. What is wrong with my logic/code?

The first if statement works fine until I add additional else if statements to it. As soon as I add the second if statement, the former if statement doesn’t work anymore. Why?


for (var i = 0; i < contacts.length; i++) {
        if (name === contacts[i].firstName && contacts[i].hasOwnProperty(prop)) {
            return contacts[i][prop];
        } else if (name !== contacts[i].firstName) {
            return "No such contact";
        } else if (!contacts[i].hasOwnProperty(prop)) {
            return "No such property";
        }
    }

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36.

https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/profile-lookup

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 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

Remember that as soon as a return statement is executed, the function is exited.

Your function always returns after checking the first item in contacts.

@KevinG I have the exact same doubts. In the end, I completely understand the solution that FCC provides, but I don’t understand why your code (which is identical to mine) doesn’t work.

@ArielLeslie In that case, wouldn’t it be the first return statement (meaning return contacts[i][prop]) in the function the first to be executed? It appears to me that there is something wrong with that line that in the end it evaluates as false.

Anyone?