Basic JavaScript #104: Profile Lookup (help)

I’ve completed this exercise, but I’m left with one question.

This code does work:

function lookUpProfile(name, prop) {
  for (let 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';
}

This code does not work:

function lookUpProfile(name, prop) {
  for (let i = 0; i < contacts.length; i++) {
    if (contacts[i].firstName === name && contacts[i].hasOwnProperty(prop)) {
      return contacts[i][prop];
    } else if (contacts[i].firstName === name) {
      return 'No such property';
    } else {
      return 'No such contact';
    }
  }
}

The only difference that seems important, at least to my novice eyes, is the return 'No such contact'; statement being outside the for loop in the code block that passes, but I don’t understand why that makes a difference.

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

Challenge: Profile Lookup

Link to the challenge:

else in the wrong solution would be executed on the first contact that doesn’t satisfy first two conditions, and it will not go to check other contacts.

it will not go to check other contacts.

I think I understand, thank you!

Look closely does the contacts array has an object with properties you are testing ?

Yes, the issue seemed to be returning the incorrect response when i !== firstName.

I mean you have to use id before accessing object from the array

You mean the index position? That’s i.

i is a variable, when it is passed to the array, it is a number. That number cycles through the array in a loop. If i = 0, then console.log(arr[i]) is equal to console.log(arr[0]), which prints the first index:

{ firstName: 'Akira',
  lastName: 'Laine',
  number: '0543236543',
  likes: [ 'Pizza', 'Coding', 'Brownie Points' ] }

Sorry I confused this challenge with another,

this will end your loop if it does not match the first contact

Oh I see, is that because return is always the end of a function?

yep, you got it, it will end loop and return from function

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