Using the bracket notation

Hi everyone!

I am currently reviewing my basic JS algorithm and was just solving the check for properties section.

My question is if I use the ‘.’ dot notation to return the value of the property the test will not past however if I use the ‘[]’ bracket notation to return the property’s value it passes the test. I assume it is because the function is passing the property as value to the argument that’s why we must use the bracket notation to return the value of the property, am I correct?

here is the code:


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

function checkObj(checkProp) {
  // Your Code Here
  if(myObj.hasOwnProperty(checkProp)) return myObj[checkProp];
  return "Not Found";
}

// Test your code by modifying these values
checkObj("gift");

There is no property called checkProp on the object, that’s why it doesn’t work.

With the dot syntax, you’re asking for a property with a key you know: myObj.gift.

With the bracket syntax you’re asking JS to do some computation to create that lookup: with myObj[checkProp], JS will look up the value of checkProp first, then if that is 'gift' for example, it will then get the value for myObj.gift

1 Like

awesome! Thanks @DanCouper

1 Like