Understanding Profile Lookup - Explanation

Tell us what’s happening:

I am having a hard time understanding the for loop when it isn’t just numbers involved. Whenever it’s just numbers it makes complete sense but I am totally stumped here. The answer given in the video is:

function lookUpProfile(name, prop){
// Only change code below this line
  for (var i = 0; i < contacts.length; i++) {
    if(contacts[i].firstName === name) {
      return contacts[i][prop] || "No such property";
    }
  }
  return "No such contact";
}
// Only change code above this line

I don’t really get what var i = 0 is supposed to be (why 0 since we are not comparing it to other numbers anyway?), or what we are plussing at the end (i++). I think if I understood what this was then i’d understand the rest of the problem a lot better. I looked up all over the forum and I wasn’t able to really find an answer to what I am looking for.

Hopefully I am being somewhat clear, I am not even sure what question I should be asking. I don’t want to move on until I’ve got this.

//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){
// Only change code below this line

for (var i = 0; i < contacts.length; i++) {
if(contacts[i].firstName === name) {
return contacts[i][prop] || “No such property”;
}
}
return “No such contact”;
}
// Only change code above this line

// Change these values to test your function
lookUpProfile(“Akira”, “likes”);



**Your browser information:**

User Agent is: <code>Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36</code>.

**Challenge:** Profile Lookup

**Link to the challenge:**
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/profile-lookup
var i = 0

i is the iterator. We start at 0 because we will start the loop with the 0th index of the contacts array.

i++

This is the incrementor. Every loop, we will increase by 1. This lets us get the next element of the array on each loop.

The first answer in the above article might help you understand it as well with more examples.

Thank you for that! Such a short and simple answer but it really cleared things up for me :slight_smile:

1 Like