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?

The line above is asking if there is a property named checkProp in the object, when the line should be checking if there is a property with the name that is the same as the value of the checkProp parameter.

Do you understand the difference?

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 ?!

For this to evaluate to true, the following object would have to be passed as the first argument to the function:

{gift: "pony", pet: "kitten", checkProp: "some value"}

Then you should review the previous challenges below:

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.