Someone explain this solution please! It's driving me nuts!

Ok, can some help me understand the solution below, from:
javascript-algorithms-and-data-structures/basic-javascript/profile-lookup project

I get that the second line is to control the loop as a counter against how many contacts objects there are.

But, I’m lost as to how we are using x in the third and fourth lines. What is the x doing with contacts?

function lookUpProfile(name, prop) {
for (var x = 0; x < contacts.length; x++){
if (contacts[x].firstName === name) {
if (contacts[x].hasOwnProperty(prop)) {
return contacts[x][prop];
} else {
return “No such property”;
}
}
}
return “No such contact”;

I would greatly appreciate some wisdom as, I can’t seem to figure it out for the life of me…

contacts is an array of objects, it’s just indexing into the array to get at each object.

var contacts = [
    {
        "firstName": "Akira",
        "lastName": "Laine",
        "number": "0543236543",
        "likes": ["Pizza", "Coding", "Brownie Points"]
    },
    {
        "firstName": "Harry",
        "lastName": "Potter",
        "number": "0994372684",
        "likes": ["Hogwarts", "Magic", "Hagrid"]
    },
];

First loop: x === 0 so contacts[0] gives you the first element, which is this object:

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

contacts[0].firstName === "Akira"

Next loop: x === 1 contacts[1] gives you the second element, which is this object:

{
  "firstName": "Harry",
  "lastName": "Potter",
  "number": "0994372684",
  "likes": ["Hogwarts", "Magic", "Hagrid"]
}

contacts[0].firstName === "Harry"

And so on.

The hasOwnProperty is to check the specified property is the objects own property (as opposed to inheriting it).

1 Like

Doh. I was way over thinking it. Was a numerical place holder to cycle to contacts object.

Thank you!!!