Using the bracket notation

Using the bracket notation
0

#1

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");


#2

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


#3

awesome! Thanks @DanCouper