Testing Objects for Properties - Meaning, if any, for syntax difference

The below code passes the tests without any issues.

I used myObj[checkProp]

in the return statement if condition is true.

However, I also tried myObj.checkProp but this does not work.

Why is there a difference between the choice of using the dot operator vs bracket operator?




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

function checkObj(checkProp) {
 
 var result = myObj.hasOwnProperty(checkProp);

  if (result == true){
    return myObj[checkProp]
  } else {
return "Not Found"
  }
  }

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/testing-objects-for-properties

myObj.checkProp search literally for a key called checkProp instead with bracket notation what is inside the brackets is evaluated and so if it is a variable the value of the variable is used as prop name

1 Like