function lookUpProfile(name) {
for (var i = 0; i < contacts.length; i++) {
if (contacts[i].firstName === name) {
return contacts[i][name]; // does not return the complete obj
}
}
return "Not found";
}
Okay, let’s take another look at your code (which I’ve run through a formatter to get rid of the extra spacing).
for (var i = 0; i < contacts.length; i++) {
- This line tells the code to loop, or iterate, through the contacts
array.
if (contacts[i].firstName === name) {
- This line tells the code to check if the object (contacts[i]
) has a value in the property firstName
that matches the value of name
- the argument we passed in to the function.
return contacts[i][name];
- IF the previous check is true, this line says "Give back the value of contacts[i][name]
.
return "Not found";
- If that previous check is never true, once the loop has gone through the entire array, this line will say “Tell me you didn’t find a contact”.
So, now that we’ve taken a look at the logical flow of your code, let’s take a look at the live function call: lookUpProfile("Kristian")
. Here, the value of name
is "Kristian"
- this is important as we will need to remember this.
The function begins with the loop. It checks contacts[0]
first - what’s the value of the firstName
property? "Akira"
. That does not match the value of name
we gave, so it loops again. It checks contacts[1]
- the firstName
property here is “Harry”, which does not match. On to contacts[2]
- the firstName
property is “Sherlock”, which does not match. Finally contacts[3]
- the firstName
property is “Kristian”… we have a match! Great! Let’s return contacts[i][name]
.
Our return statement evaluates to contacts[3]["Kristian"]
. We know contacts[3]
exists, but what is the value of the Kristian
property? Wait… there isn’t one! The contact object does not have a Kristian
property… So the value is undefined
, which is what your function will return.
The return statement will need to be adjusted to return the correct value.
Now that we’ve looked at the logical flow of your function, we have another thing to look at. When you call lookUpProfile("kristian")
you are getting "Not found"
as your return value. Why? Because "kristian"
and "Kristian"
are not the same thing - in JavaScript, the casing of strings is important.
As one final note, the function you have written has been malformed from the challenge seed. The function should take two parameters, a name
and a prop
. You’ve removed the prop
parameter, and will not be able to pass the challenge until that is corrected.