I'm studying JavaScript on my own and I started by reading tutorials and books (like Eloquent) and articles (on Medium for example). I'm also doing some free courses, two in particular: freeCodeCamp and CodeAcademy.
Today I had to face a contact list exercise on CodeAcademy, and I am not sure I understood it properly.
After some hints, this is the final code I came up with:
var friends = {
bill: {
firstName: "Bill",
lastName: "Gates",
number: "555 555 555",
address: ["One Miscrosoft Way", "Redmond", "WA", "98052"]
},
steve: {
firstName: "Steve",
lastName: "Jobs",
number: "333 333 333",
address: ["Apple's street", "Silicon Valley", "SV", "87368"]
}
};
var list = function(friends) {
for (var firstName in friends) {
console.log(firstName);
}
};
var search = function(name) {
for (var key in friends) {
if (friends[key].firstName === name) {
console.log(friends[key]);
return friends[key];
}
}
};
list(friends);
search("Steve");
.as-console-wrapper { max-height: 100% !important; top: 0; }
I understood the var friends object and the first function. But what about the second function? Why do I need to use "name" and "key" words if they're not in the contact list. Could you explain me what the code really does?
Also, at the end of the exercise, CodeAcademy put this final code to do something I imagine:
list(friends);
search("Steve");
What exactly is it?
Well in this function:
var search = function(name) {
for (var key in friends) {
if (friends[key].firstName === name) {
console.log(friends[key]);
return friends[key];
}
}
};
Variable key
refers to each key of object friends
in every iteration, which means it's value is 'bill' in first iteration and 'steve' in second iteration.
name
is a parameter of this function search
, it don't have an actual value until function is executed like search('Steve')
, see you assign the value 'Steve'
to it.
So, list(friends)
print 'bill' and 'steve' in console, and search('Steve')
will print this object:
{
firstName: "Steve",
lastName: "Jobs",
number: "333 333 333",
address: ["Apple's street", "Silicon Valley", "SV", "87368"]
}
and return it.