Javascript function / syntax question

In this javascript problem, I am tasked to create a function that checks if a first name and its prop is in the data pool. This is the solution to the assignemnt:

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

What I would like to know is why I assign x = 0 to this problem, what does that mean/ do? Another question is, in different problems FCC uses i not x, are they interchangable like it would be in algebra? I don’t understand why I would use the .length property here, I thought that tells me the length of the array sets? Am I correct in thinking that x++ moves the function forward to the next array set?

  **Your code so far**

// Setup
const 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

// Only change code above this line
}

lookUpProfile("Akira", "likes");
  **Your browser information:**

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

Challenge: Profile Lookup

Link to the challenge:

Hi @OneStew !

I added spoiler tags to the code since it is the answer to the challenge.


That represents the initialization.

You can use use whatever variable name you want.
Most people use i.
If you have a nested for loop than they will use j for the inner loop.

But x works to.

So contacts.length represents the length of the array.

Contacts is an array of objects.

The length of that array is four.

In our for loop, our condition here is saying while x < contacts.length run that loop.
Another way to look at it would be say while x<4 since contacts.length is 4.

While that condition is true the loop will run and the computer will check the if statements.

Contacts is an array.
It is an array of objects.

Everytime we increment x then we move to the next object in our array.

If you want to review more about for loops then you can look at this tutorial
https://www.javascripttutorial.net/javascript-for-loop/

Hope that helps!

1 Like