Profile Lookup - why do we use hasOwnProperty for prop and not firstName as it is also a property?

Tell us what’s happening:
if (firstName === contacts[i].firstName){
if (contacts[i].hasOwnProperty(prop)){
Why do we use hasOwnProperty for prop and not firstName???

Your code so far

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"]

// Only change code below this line

function lookUpProfile(firstName, prop){ 
    for (var i=0; i < contacts.length; i++){ 
        if (firstName === contacts[i].firstName){ 
            if (contacts[i].hasOwnProperty(prop)){  
                return contacts[i][prop]; 
            }else {
                return "No such property";
                return "No such contact";

// Only change code above this line

// Change these values to test your function
lookUpProfile("Akira", "likes");

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36.

Link to the challenge:

Because ‘contacts[i].firstName’ will return the ‘firstName’ property if the object contains such property(i.e it evaluates to true and your code runs whats inside the ‘if statement’ , in this case ‘return contacts[i][prop]’), but if the object does not contain such property it will return ‘undefined’ not false, therefore your code does not run whats in the ‘if or else statement’, it just stops and returns undefined. However ‘contacts[i].hasOwnProperty(prop)’ checks if ‘contact[i]’ has a property of ‘number or likes or lastName’ if it does, ‘hasOwnProperty’ returns true and the code inside the ‘if statement’ runs, else it returns false and the code inside the else statement runs.

Basically the ‘hasOwnProperty’ method returns true or false when used properly

1 Like

If one of the contacts did not have a firstName property and you wrote the following:

if (firstName === contacts[i].firstName){

the contacts[i].firstName would evaluate to undefined and since the argument firstName is not equal to the value undefined, it would still evaluate to false anyway.