This piece of code comes from a freeCodeCamp challenge. And it works. But I need some clarification. In the exercise, it is about reading a json array to extract the value of the given firstName property when calling the lookUp function. Also, check such property exists before reading its value.
When contacts.some declares the callback function (arg) {...}, it seems that 'arg' already knows the 'firstName' and 'prop' parameters passed when calling the lookUp function.
//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 lookUp(firstName, prop) {
// Only change code below this line
var answer = "No such contact";
contacts.some(function(arg) {
if (arg.firstName === firstName && arg.hasOwnProperty(prop) === true) {
answer = arg[prop];
} else if (arg.hasOwnProperty(prop) === false) {
answer = "No such property";
}
});
return answer;
// Only change code above this line
}
// Change these values to test your function
lookUp("Kristian", "lastName");
I do not understand where the magic is. Why does 'arg' contain the value of both parameters? Could anyone explain how this happens?
Thanks in advance. Carlos.