Testing Objects for Properties - question

Hi, maybe a stupid question, but I don’t understand why this code works:

function checkObj(obj, checkProp) {
  if (obj.hasOwnProperty(checkProp)) {
    return obj[checkProp];
  }
  return "Not Found";
}

but this code doesn’t:

function checkObj(obj, checkProp) {
  if (obj.hasOwnProperty(checkProp)) {
    return obj.checkProp;
  }
  return "Not Found";
}

I thought obj[checkProp] and obj.checkProp would give the same result, but the second answer isn’t accepted. I’d appreciate if someone could explain the difference :slight_smile:

You might want to review the couple lessons before this that explain the difference between bracket notation – this[one] – and dot notation – this.one

With dot notation, we look up the property named literally what comes after the dot.

const person = {
  name: "Colin",
};

console.log(person.name); // "Colin"

With bracket notation, the expression in the brackets gets evaluated and coerced to string before being used to look up the property of the object.

So you can do things like string concatenation:

console.log(person["n" + "a" + "m" + "e"]); // "Colin"

Or throw a variable into the brackets:

const theKey = "name";
console.log(person[theKey]); // "Colin"

Now I get it. Thanks A LOT! :smiley:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.