Basic JavaScript: Profile Lookup [Understand better the logic]

Tell us what’s happening:

Hey guys, I’ve complete the challenge, but I’d like to understand better the logic behind. :slightly_smiling_face:

Spoiler here:

1:

  • a. You call the function with name and prop arguments
  • b. The for loop iterate through the contacts array (i < contacts.length)
  • c. The if statement checking if the passing arguments are match with the number contacts[i] Array
  • d. if they match so function return the prop value, if not it returns the else strings

2:

  • If the first if statement is true > go and check the nested if statement > if the nested if statement is true > return prop value > otherwise > return the else statement

  • The nested if statement replace the need of the && (and) operator

3:
How the loop works in this challenge:

  • When the loop start running > the loop check if his first number (var i = 0) match with the first if statement condition contacts[i] and name parameter > if not > jumping back from the if statement to the loop, and continue like this until the loop number match with the if statement > otherwise executing the else statement.

Got it right?

And spoiler here:

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

// Change these values to test your function
console.log(lookUpProfile("Harry", "likes"));

I could use also else if statement, but it would make the code longer and less cleaner.

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/profile-lookup

Your logic is sound. Although I am not sure what “continue like this until the loop number match”

Thank you for the reply

I mean (spoiler):

Jumping from the if statement back to the loop and back, until the loop number ( the i ) match with the if statement condition

for (var i = 0; i < contacts.length; i++) {
if (contacts[i] .firstName === name) { .