Using bracket notation inside a function to reference an object

why can’t we use the dot notation inside a function using it’s parameters?

Your code so far

// Setup
var myObj = {
  gift: "pony",
  pet: "kitten",
  bed: "sleigh"

function checkObj(checkProp) {
  // Your Code Here
  if (myObj.hasOwnProperty(checkProp)) {
    return myObj.checkProp;
  } else {
    return "Not Found";
  return "Change Me!";

// Test your code by modifying these values

instead the of returning the property’s name it is returning undefined, I would also like to know why it’s doing that.
thank you.

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36.

Link to the challenge:

because myObj.checkProp will search literally for a property called checkProp, and as there is no property called that, myObj.checkProp is undefined
instead what is inside the brackets is evaluated, and if it is a variable than it will be substituted with its value when accessing the property


I believe with dot notation, it is expected that the property name after the dot will literally match the property name, so you cannot use a variable to check it that way. However, using myObj[checkProp] will evaluate the property names against the argument/variable checkProp.

1 Like