Testing Objects for Properties: Dot or Bracket notation

Hello,

can anybody explain to me, please, why this code:

function checkObj(obj, checkProp) {
  // Only change code below this line
  if (obj.hasOwnProperty(checkProp)) {
    return obj.checkProp;
  }
  else {
    return "Not Found";
  }
  // Only change code above this line
}

doesn’t pass, while this code:

function checkObj(obj, checkProp) {
  // Only change code below this line
  if (obj.hasOwnProperty(checkProp)) {
    return obj[checkProp];
  }
  else {
    return "Not Found";
  }
  // Only change code above this line
}

does pass?

The only difference between the two is that in the first code I used .dot notation for the return property inside the if function and in the second I used [bracket notation] for the same thing.
Why does one code pass and the other doesn’t? They both do the absolutely same thing, don’t they?

When you use dot notation you are looking for something literally named “checkProp” in the obj that was passed to the function. With bracket notation you can use variables that store a value to access the obj.

So if you had a variable called someValue and you typed obj.someValue its looking for the property "someValue" in obj. But if i say let sameValue = 'this string' then type obj[someValue] im looking for the property "this string" stored in obj, not "someValue" literally.

2 Likes