Iterating through an array in JavaScript (the Profile Lookup problem)

I am trying to iterate through an array of objects (the freeCodeCamp Profile Lookup problem), and the part of my code that should run if the name and property are found does not run for some reason. The code works fine if there is no such contact, or no such property, but if both are found, it returns nothing. I suspect that I am doing something wrong syntax-wise when I check for the existence of the needed property, but I can’t tell what. Below is the code that isn’t working:

 function lookUpProfile(firstName, prop){
    // Only change code below this line
    var foundName = false;
    var bookmark = -1;
    for (i = 0; i < contacts.length; i++) {
  if (contacts[i].firstName == firstName && contacts[i].hasOwnProperty(prop)) {
    foundName = true;
    bookmark = i;
  } else if (contacts[i].firstName == firstName) {
    foundName = true;
  }
}
  if (foundName === true && bookmark !== -1) { //both contact and property found
    return contacts[bookmark].prop;
  } else if (foundName === true && bookmark == -1) { // contact found, but not property
    return "No such property";
  } else {
    return "No such contact";
  }
  }

What is wrong with this code? For some reason, it works only if something isn’t found (or, I suspect, the iteration never runs past the first object in the array).

Ok so first off, I would always copy this code into the JS console (in Chrome), and see what you are getting as return values. From the console, it looks like your code is returning “undefined” when both things are true.

So why would that be? Especially since we know that the property does exist on the object. It would appear that we are attempting to access the property incorrectly. When using for loops, you must use bracket notation instead of dot notation.

Right now, your code is literally looking for the .prop property on contacts[bookmark].prop, but as we figured out, the .prop property doesn’t exist! To access properties using variables (the prop argument you passed), you need to use bracket notation.

Give it a try!

1 Like

Thanks! replacing the dot notation with the bracket notation in the first return statement made everything work. I’ve never heard about this nuance of for loops before.

Yeah I should have worded that a bit differently (it was late). You have to use bracket notation if you are trying to access a property with a passed argument.

This is fine:

contacts[bookmark].name 

But if you are trying to pass an argument:

function combContacts (prop) {
   return contacts[bookmark].prop;
}

If you passed ‘name’ as your argument:

combContacts("name");

You would get “undefined” returned as your function is looking for a literal property called “prop”. If you want to access properties using a passed argument, you gotta use bracket notation.