Basic JavaScript - Profile Lookup

I do not understand why this code does not work, i checked other solutions and i think this is right but seems to be its not.

// Setup
const 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(let i = 0; i < contacts.length; i++){
    if(name != contacts[i]["firstName"]){
      return "No such contact"
    } else if(!contacts[i].hasOwnProperty(prop)){
      return "No such property"
    } else{
      
      return contacts[i][prop];
    }

  }
  // 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/116.0.0.0 Safari/537.36

Challenge: Basic JavaScript - Profile Lookup

Link to the challenge:

This says, in words, “As soon as you find a contact whose first name does not match, give up and return the string ‘No such contact’ immediately”.

A return statement immediately stops your function.

But isn’t that supposed to happend?

You want the function to give up if the very first contact doesn’t match and stop before looking at any other contacts? That doesn’t sound right.

but, it also stops the iteration when it reachs the return?

Thats what I am saying. Your loop stops whenever there is a return statement.
You do not want the loop to stop if you only find one contact that doesn’t match.

ohhh, i thought the return stopped only the if, not also the for

The return stops the entire function.

You can use an editor such as vscode to debug through breakpoints. The editor will tell you all the information, what is the value of the variable at each step and whether the loop is broken out.

Does using console.log works there ?

You can console.log but it won’t help you pass the challenge requirements. You need to return the right string, at the right time.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.