Basic JavaScript - Testing Objects for Properties

Tell us what’s happening:
Hey, just wondered if someone can tell me what’s wrong with my code here. I am trying to return the value of checkProp if checkProp is present in the object and return the string “Not found” if it isn’t present.

Your code so far

function checkObj(obj, checkProp) {

// Only change code below this line

if (obj.hasOwnProperty(checkProp) == true) {
  return checkProp; 
}
else {
  return "Not found";
}

// Only change code above this line

}

checkObj({gift: “pony”, pet: “kitten”, bed: “sleigh”}, “gift”);

function checkObj(obj, checkProp) {
  // Only change code below this line
  if (obj.hasOwnProperty(checkProp) == true) {
    return checkProp; 
  }
  else {
    return "Not found";
  }
  
  // Only change code above this line
}

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


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36

Challenge: Basic JavaScript - Testing Objects for Properties

Link to the challenge:

Right now you are returning checkProp, which is the property. They said to return the value of that property, not the property itself.

How would you access and return the value associated with checkProp?

Previously when I’ve returned a value from a function I’ve used something like
return array[function argument]. In this case I want to return the object and the input which is the function’s argument, so I’ve tried return checkObj(checkProp) but that doesn’t work.

This is close but the syntax is a little off. I suggest you review this lesson on objects.

Yeah that’s close.

But checkProp can’t be a property of checkObj, because checkObj is not an object.

The property checkProp is a property of something else. That something needs to be an object.

I really appreciate the help and pushing me to work it out myself. But if I’m just shown the code I will remember for next time. Already spent well over 1 hour on this so I need to balance the challenge with progress . This is the first time I’ve gotten stuck like this. Thank you

I understand. I usually prefer just getting the answer and figuring out why it works, myself.

If the object has the property, you need to return obj[checkProp].

Thank you very much. Yes it makes total sense now.

1 Like

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