Why this code is only working for [0] array and not for others. I think this is correct code

Tell us what’s happening:

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){
// Only change code below this line
for(var i = 0; i < contacts.length; i++){
if (contacts[i].firstName === name){
            return contacts[i][prop] || "No such property"; 
            }
            return "No such contact";
}
// Only change code above this line
}
console.log(lookUpProfile("Harry", "lastName"));


Your browser information:

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

Challenge: Profile Lookup

Link to the challenge:

you have a return statement inside the loop that will always be trigger (if one before is not triggered), that means that as soon as the return statement is execute, the function stops and return a value
the loop never go past its first iteration

2 Likes

Hey there!

I am not sure if the curriculum has mentioned it yet but, as @ilenia mentions, a “return” statement ends the execution of a function. I know from personal experience that the explanation for the return statement is quite some chapters away from the first time it is needed and it makes some exercises confusing.

The curriculum is not always in order and it speaks of some terms or functionalities/rules after you needed to know at least a bit about them.

Nevertheless, keep going. It will all fall in place little by little with time.

Happy coding. :slight_smile:

1 Like