This is my answer in freecodecamp "Basic Javascript: Profile Lookup" (third day trying javascript using Udemy and freecodecamp).
My problem with the code is the huge number of lines on my lookUpProfile
function. I would like to minimize the lines of code of my lookUpProfile
function, can you suggest me ways to achieve that?
//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 lookUpProfile(firstName, prop){
// Only change code below this line
var contain = 0;
if(firstName == "Akira"){
contain = 0;
if(contacts[contain].firstName == firstName)
if(contacts[contain].hasOwnProperty(prop))
return contacts[contain][prop];
else
return "No such property";
else
return "No such contact";
}
else if(firstName == "Harry"){
contain = 1;
if(contacts[contain].firstName == firstName)
if(contacts[contain].hasOwnProperty(prop))
return contacts[contain][prop];
else
return "No such property";
else
return "No such contact";
}
else if(firstName == "Sherlock"){
contain = 2;
if(contacts[contain].firstName == firstName)
if(contacts[contain].hasOwnProperty(prop))
return contacts[contain][prop];
else
return "No such property";
else
return "No such contact";
}
else if(firstName == "Kristian"){
contain = 3;
if(contacts[contain].firstName == firstName)
if(contacts[contain].hasOwnProperty(prop))
return contacts[contain][prop];
else
return "No such property";
else
return "No such contact";
}
else
return "No such contact";
// Only change code above this line
}
// Change these values to test your function
lookUpProfile("Akira", "lastName");