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

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

#1

Hi,

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
checkObj("dog");

#2

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


#3

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


#4

Passing a property parameter in hasOwnProperty?


#5

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


#6

@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.


#7

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


#8

this worked for me.

function checkObj(checkProp) {
if(myObj.hasOwnProperty(checkProp))
return myObj[checkProp];
else
return “Not Found”;

}