Testing Objects for Properties https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/testing-objects-for-properties

Tell us what’s happening:

Your code so far


// Setup
var myObj = {
  gift: "pony",
  pet: "kitten",
  bed: "sleigh"
};

function checkObj(checkProp) {
 if(myObj.hasOwnProperty(checkProp){
   return myObj.checkProp;
 }else{
   return "Not Found";
 }
}

// Test your code by modifying these values
checkObj("gift");

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/testing-objects-for-properties

1 Like

You are also missing a closing round bracket

This is your problem here. You are returning the literal property “checkProp” on myObj, rather than the property named by the variable checkProp. You need to be using bracket notation instead. This should be covered in a previous challenge: Accessing Object Properties with Variables

2 Likes

That’s very helpful! I had the same problem! Thanks!

This article is SUPER helpful, thanks!!

This works for me… (took a long time to figure out!)…

function checkObj(obj, checkProp) {

// Only change code below this line

var obj = {

gift: "pony",

pet: "kitten",

bed: "sleigh",

city: "Seattle"

};

if (obj.hasOwnProperty(checkProp)){

return obj[checkProp];

}

else {

  return "Not Found";

}

// Only change code above this line

}

the function parameter is called obj, you are creating an object of the same name inside the function: you are overwriting the function parameter, so making your function not reusable. I suggest you fix it, as what you are doing is really bad practice

I wrote only this:

if(obj.hasOwnProperty(checkProp)) {

  return obj[checkProp];}

  else return "Not Found";

but the question is why we don’t put quotes inside the parenthesis of hasOwnProperty and inside brackets of obj[checkProp].
Thanks in advance.

checkProp is a variable, "checkProp" is a string

if you want to check for literally a property named "checkProp" you use the quotes

if instead you want to use the value inside the variables, then you do not use the quotes

1 Like