How is this working if Seattle: "city" is not ever defined in the object?

Tell us what’s happening:
I am beyond confused as to what is going on in this challenge after spending hours on it, I looked at the solution. Although it runs, I just don’t understand how it works if Seattle: “city” isn’t defined in the object. Am I missing something?

Your code so far


function checkObj(checkProp) {
// Only change code below this line
// Setup
var myObj = {
gift: "pony",
pet: "kitten",
bed: "sleigh"
};



if (myObj.hasOwnProperty(checkProp) == true) {
  return myObj[checkProp];
} else {
  return "Not Found";
}
}
return "Change Me!";
// Only change code above this line
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36.

Challenge: Testing Objects for Properties

Link to the challenge:

I’m not sure what you are asking - the code you’ve provided does not appear to run properly.

Hey thanks so much for your quick response. And sorry for not explaining properly. One of the conditions for this code running successfully is:

checkObj({city: "Seattle"}, "city") should return "Seattle" .

I guess I copy and pasted the wrong code. Should be this. I just tested it again and I’m still unsure how it works.

var myObj = {

gift: “pony”,

pet: “kitten”,

bed: “sleigh”

};

function checkObj(obj, checkProp) {

if(obj.hasOwnProperty(checkProp)) {

return obj[checkProp];

} else {

return "Not Found";

}

// Only change code below this line

return “Change Me!”;

// Only change code above this line

}

Okay, let’s go line by line here. :slight_smile:
function checkObj(obj, checkProp) {
This line takes the obj and checkProp arguments. In your example, obj is {city: "Seattle"} and checkProp is "city".

if(obj.hasOwnProperty(checkProp)) {
This line checks if the obj has a property that matches checkProp. In our example this is true, as the object has a property called city.

return obj[checkProp]
When the if statement above is true, the function returns the value of the checkProp property of obj. In our example, the value for the city property is "Seattle".

else {return "Not Found";}
This says if the if statement is false, then the function returns "Not Found".

Does this answer your question? :slight_smile:

1 Like

Yes I think so. Thanks, Nicholas.