I've been doing the coding challenge from freecodecamp.org. Here it is:
//create a function where you pass a name and a property, and the value of the prop will be returned
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 lookUpProfile(name, prop) {
for (var i = 0; i < contacts.length; i++) {
if (name == contacts[i].firstName) {
return console.log(contacts[i][prop]) || console.log('No such property');
}
}
return console.log('No such contact');
}
lookUpProfile("Akira", "likes");
My problem is that instead of console.logging the function itself, I wanted to do it inside the function so the values are strings. However, this kept marking undefined and I don't get why. Here's the correct form of the code
//create a function where you pass a name and a property, and the value of the prop will be returned
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 lookUpProfile(name, prop) {
for (var i = 0; i < contacts.length; i++) {
if (name == contacts[i].firstName) {
return contacts[i][prop] || 'No such property';
}
}
return console.log('No such contact');
}
console.log(lookUpProfile("Akira", "likes"));
Also, I don't get how an 'or' (||) statement works as an 'else' statement and why does the last return only returns the value if the if statement is false. Can anybody help me please?