Testing Objects for Properties explain

Tell us what’s happening:

Hi there,
In the code below why I am not able to access the property of an object by dot notation while bracket notation helped me to pass the test.

answer = obj.checkProp

Please explain.

Your code so far

function checkObj(obj, checkProp) {
// Only change code below this line
var answer = "";
if (obj.hasOwnProperty(checkProp) === true){ 
  answer = obj.checkProp
else {
  answer = "Not Found"
return answer;
// 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/87.0.4280.88 Safari/537.36.

Challenge: Testing Objects for Properties

Link to the challenge:

Because checkProp is a variable that contains a string. obj.checkProp is looking for a property named checkProp rather than whatever value the variable checkProp contains.

By using brackets, we don’t need to know which property we want, we can represent it in those brackets as a string. That’s the key - you don’t really care about the variable name checkProp, you care about what’s in it.

1 Like

Thank you for your reply @snowmonkey