Basic JavaScript - Testing Objects for Properties

the first if of the code doesn’t work but the second one does, what’s the difference? I thought using . or to access the object property was the same

  **Your code so far**
function checkObj(obj, checkProp) {
// Only change code below this line
if (obj.hasOwnProperty(checkProp))
{
  return obj.checkProp;
}
else 
{
  return "Not Found";
}

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 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36

Challenge: Basic JavaScript - Testing Objects for Properties

Link to the challenge:

Not quite. Dot notation is used when you know the exact name of the property you are looking for. You access the property with a string. So in this case:

return obj.checkProp;

You are saying “return the value of the property ‘checkProp’ in the object.” checkProp is a string which is the name of the property you are looking for in the object.

But that isn’t what you want to do here. The actual name of the property you want in the object is stored in the variable checkProp. When you use a variable to access a property in an object then you have to use brackets.

return obj[checkProp];

This says “get the value stored in checkProp and then return the value of that property in the object.” It’s a two step process. First you get the value stored in checkProp. Then you use that value as the property you want get from the object.

2 Likes

I see! thank you so much!