JavaScript Basics: Profile Lookup

function lookUpProfile(name, prop){
// Only change code below this line
for (var 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";
// Only change code above this line
}

Hi Everyone!

I got all the code correct the first time, except for the last line:

return "No such contact";

I was trying to put it after the outer if statement’s closing bracket like so:

function lookUpProfile(name, prop){
// Only change code below this line
for (var 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";
     }
   } else {
          return "No such contact";
   }
}

// Only change code above this line
}

I just need a bit of explanation as to why that is an error. Thanks very much!

PS. I find it hilarious that it took me almost an hour to look at the hint, to find out that everything I wrote was almost identical except for that one line. It’s frustrating, BUT I LOVE IT!!! :smiley:

The difference lies in the scope where the if is called.

Inside the loop, each block of code gets called on every iteration, this means that you are running the case “No Such Contact” on every element of the loop,

but you cannot tell that the element doesn’t exist until you have actually looked “everywhere” for it. :smile:

Consider this easy example:

var a = [ 1, 2 , 3]

// I want to check for number 2
for(var i = 0; i < a.length; i++) {
  if(a[i] === 2) {
    return  "we got 2"
  } else {
    return "not number 2"
  }
}

// return "not number 2"

Will return “not number 2” since the first element is in fact 1, and we instruct the loop to exit (return) without even keep looking.

Hope this helps :+1:

2 Likes

Makes perfect sense on the first sentence. I mean, I was just looking at the ‘if else’ statement, that’s why I couldn’t figure it out. Thanks very much!