Testing Objects for Properties task // dot notation vs square brackets

This is my solution for the testing objects for properties. I was stuck trying to return the property for ages using obj.checkProp so i switched it to the square brackets as seen below. I have no idea why the dot notation didn’t work , does anyone have an explanation?

[spoiler]function checkObj(obj, checkProp) {
// Only change code below this line
if (obj.hasOwnProperty(checkProp) !== false) {
return obj[checkProp];
} else {
return ‘Not Found’;
// Only change code above this line


The object doesn’t have a property called “checkProp”. obj.checkProp means "look up the property with the key 'checkProp' on the object obj".

checkProp is a variable, it isn’t the name of a key on the object. It needs to be evaluated before the lookup happens: obj[checkProp]. If the value of checkProp is, say, “bob”, then that would evaluate to obj.bob


Thanks for the explanation!

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