Javascript basics HELPPP!

Tell us what’s happening:
Why is my code wrong???

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 && contacts[i].hasOwnProperty(prop) == true) {
        return contacts[i][prop];
        }
    else if (contacts[i].firstName == name && contacts[i].hasOwnProperty(prop) == false) {
        return "No such property"
        }
return "No such contact"
    }
}
// Only change code above this line


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/83.0.4103.61 Safari/537.36.

Challenge: Profile Lookup

Link to the challenge:

you have all three return statements inside the for loop, one is outside of the if statements so it would always execute
this means that as soon as the return statement is met when i=0 the function stops and return a value, the loop never iterate over the other elements in the array

1 Like

Wah thanks a lottt !!! I have been staring at it for quite some time. Probably too used to python where indentation matters rather than the {} haha

try to format it properly so you can still use indentation to catch stuff like this.
Many editors have the option to prettify the code with a click. For example, using the “Tidy” button of jsfiddle.net your code becomes as below and it is easier to see

function lookUpProfile(name, prop) {
  // Only change code below this line
  for (var i = 0; i < contacts.length; i++) {
    if (contacts[i].firstName == name && contacts[i].hasOwnProperty(prop) == true) {
      return contacts[i][prop];
    } else if (contacts[i].firstName == name && contacts[i].hasOwnProperty(prop) == false) {
      return "No such property"
    }
    return "No such contact"
  }
}
  // Only change code above this line
1 Like

Okay thanks! Will definitely try to improve how I format my code!

Thanks a lot. I also had the same problem.