Help - Dot Notation vs Bracket Notation -

Hello, could someone clarify why the first block of code works whilst the second doesn’t? All I’m changing is the notation in the return for the if statement.

============ First Block ============

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

function checkObj(checkProp) {
    if (myObj.hasOwnProperty(checkProp) === true) {
        return myObj[checkProp];
    } else {
        return "Not Found";
    }
}
checkObj("gift");

============ Second Block ============

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

function checkObj(checkProp) {
  if (myObj.hasOwnProperty(checkProp) === true){
      return myObj.checkProp;

  } else {
      return "Not Found";
  }
}

checkObj("gift");

When using dot notation, the property listed after the dot must be an actual property name of the object. The myObj object does not have a property named “checkProp”, so it would return undefined as a value.

1 Like

Oh, that’s very specific. Thanks for pointing that out, I don’t know how that one slipped past me in the lessons. Thank you.