Testing Objects for Properties...How can I improve this?

Testing Objects for Properties...How can I improve this?
0.0 0



I wonder what is wrong with this code:

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

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

// Test your code by modifying these values


It looks as though you aren’t passing a property parameter in hasOwnProperty i.e it should be .hasOwnProperty(prop). Does that help?


Also in your if statement you don;t have to do if(myObj.hasOwnProperty === true)) you can just do if(myObj.hasOwnProperty(propertyName))


Passing a property parameter in hasOwnProperty?


Yep, at the moment it is myObj.hasOwnProperty when it should be myObj.hasOwnProperty(checkProp) . Essentially you need to pass the property you would like to check as the parameter. More info on the mozilla website


@cmwebby is correct. In the function you are using the parameter checkProp to pass in the argument for the function. You want to use the hasOwnProperty method on the argument “dog” in this case.

Also, if you just use

return hasOwnProperty(checkProp);

you will get a true/false value even without the if statement. As it stands now, you are returning checkProp, or “dog” from this function. I don’t know if that was your intent.


I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.


this worked for me.

function checkObj(checkProp) {
return myObj[checkProp];
return “Not Found”;