Loop trouble with going through array

hi, I don’t really understand why is it not working with my forEach method ?


// 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) {
contacts.forEach (contact => {
  if (name === contact.firstName) {
    if (contact.hasOwnProperty(prop)) {
       return contact[prop];
    } else {return "No such property"}
  } else { return "No such contact"}
})
}
lookUpProfile("Harry", "lastName")

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Safari/605.1.15.

Challenge: Profile Lookup

Link to the challenge:

Hi and welcome to the forum.

Your code will stop running the very first time you encounter a return statement, which means you will not traverse the entire array.

1 Like

does that mean that I can’t use forEach for solution of this problem ? thanks for quick reply

Nope, it means you can’t return “No such contact” before you check everything in the array.

1 Like

I’m not really sure that @JeremyLT 's explanation is correct

for what I see, your function does not have a return statement as the return statements inside forEach is just for the callback of forEach , not for the lookUpProfile function

1 Like

Woops, for some reason I mixed up forEach and for... in

ok, I’ve put forEach into variable, so now it looks like

function lookUpProfile(name, prop) {
 let lookup = contacts.forEach (contact => {
   if (name === contact.firstName) {
     console.log(contact.firstName)
     if (contact.hasOwnProperty(prop)) {
      console.log(contact[prop])
       return contact[prop]

     } else {return "No such property"}
    } 
    else { return "No such contact"}
  })
return lookup
  }

Is that correct ? my other question is why I’m getting an undefined in the end of the function

thanks

forEach doesn’t have a return value. Assigning something to the results of a forEach will always be undefined.

2 Likes

forEach is not the most indicated way to solve this algorithm

1 Like

I’m sorry for the confusion - I thought that you were using a for loop. I’d honestly recommend solving these challenges with a basic loop and then try to refactor to fancy high order functions later. Basic loops are ok and you don’t have to use fancy high order functions like forEach just because other people really love them.

1 Like