Testing Objects for Properties Javascript

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

function checkObj(checkProp) {
// Your Code Here
return (myObj[checkProp] ? myObj[checkProp] : “Not Found”);
// Test your code by modifying these values

Like that I can pass to the next level, but if I try different (2 different ways) it doesn’t allow me…what’s the problem?

if I try to write :
return (myObj.hasOwnProperty(“checkProp”) ? myObj[checkProp] : “Not Found”);
if(myObj.hasOwnProperty(“checkProp”)) {
return myObj[checkProp];
return “Not Found”;

it doesn’t want…

Could someone help me to understand what’s the problem. Why myObj.hasOwnProperty(“checkProp”) it show false all the time?
Why myObj[checkProp] is good and myObj.hasOwnProperty(“checkProp”) is not?

Thank you in advance

I found the answer… myObj.hasOwnProperty(“checkProp”) should be without inverted commas myObj.hasOwnProperty(checkProp)

more than 10 hours I could figure out what’s the problem.

However can someone explain the difference between with and without inverted commas.

Thank you

"checkProp" is a string, while checkProp is a variable that holds a string.

var checkProp = "test";
myObj.hasOwnProperty("checkProp") searches for a property named "checkProp"
myObj.hasOwnProperty(checkProp) is equal to myObj.hasOwnProperty("test") searches for a property named "test"

So if you use "checkProp" JS takes it as a string, but if you use checkProp it will think it is a variable and replace it with the actual value this variable holds ("test"). Note: if the checkProp is not defined and will give an error.

Thank you very much BenGitter.

it’s much easier to work now :). I have to pay more attention, I probably missed that.

Thanks. Have a great day :wink: