Testing object for properties (dot notation does not work))

Tell us what’s happening:
I was doing the exercise from Basic JavaScrip/ Testing for object properties and for some reason when I try to return a value using dot notation it would not work. I don’t understand why I won’t.

Your code so far


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

// Only change code above this line
}


If I change it to bracket notation, like down below it works. It does not make sense to me.


function checkObj(obj, checkProp) {
// Only change code below this line
if(obj.hasOwnProperty(checkProp) === true){
  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_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4209.0 Safari/537.36.

Challenge: Testing Objects for Properties

Link to the challenge:

You can’t use dot notation when your property name is inside a variable. You must use bracket notation, like this:
obj[checkProp]

When you say obj.checkProp , that means obj has a property called checkProp. It’s the equivalent of obj[“checkProp”].

1 Like

Thanks you so much @blackturtlejames , that was very helpful!
I also found this article for a more elaborated explanation. Just in case anyone else runs into the same question and want to understand this behavior: