Basic JavaScript - Testing Objects for Properties

Tell us what’s happening:
Describe your issue in detail here.
I’m not understanding the error it is showing and what to rectify here ??
Your code so far

function checkObj(obj, checkProp) {
  // Only change code below this line
  // return "Change Me!";
if(obj.hasOwnProperty("checkProp")) {
  return obj["checkProp"];
}
else {
  return "Not Found";
}
  // 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/108.0.0.0 Safari/537.36

Challenge: Basic JavaScript - Testing Objects for Properties

Link to the challenge:

1 Like

Can you explain, what are you trying to do over here?

If checkProp property exists in the object then return the value of the property checkProp else return “Not Found”

If these are the arguments passed to the function.

checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "gift")

You should be checking whether the property gift exists in the object {gift: "pony", pet: "kitten", bed: "sleigh"}

But you are always checking whether the property checkProp exists in any given object.

This is because you are not using the parameter checkProp anywhere in your function.

Sorry, I’m not understanding how to use “checkProp” and where is it asked to use it ?!

oh okay, where could i run these codes and try manipulating it for my understanding ?

Yeah, I’ll go through them now:)

obj.hasOwnProperty(“checkProp”)

"checkProp" means a string. It will check for a specific property named checkProp.

obj.hasOwnProperty(checkProp)

checkProp means a variable. It will check for a property associated with the argument checkProp.

1 Like

Yeah, I made that change but unable to figure out why it isn’t passing for 3 cases.

// Only change code below this line
// return “Change Me!”;
if(obj.hasOwnProperty(checkProp)) {
return obj.checkProp;
}
else {
return “Not Found”;
}

// Only change code above this line
}

It worked for obj[checkProp]; instead of obj.checkProp;

Dot notation will not work with variables. When you say obj.checkProp its looking in obj for a property named “checkprop”. But you want to use the value stored in checkProp to check if its in obj, so you have to use bracket.

1 Like

Yes, what @Lego_My_Eggo said.

When accessing properties with dot notation, you need to use brackets when the property name is a variable.

It’s just a Javascript rule.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.