0

function checkObj(obj, checkProp) {

  if (obj.hasOwnProperty(checkProp)) {
    return obj.checkProp;
  }
  return 'Not Found';
}

console.log(checkObj({ gift: 'pony', pet: 'kitten', bed: 'sleigh' }, 'gift'));

The code above gives an output of underfined whereas it works perfectly fine if it's

 return obj[checkProp]

Why does this happen? Thanks.

adiga
  • 34,372
  • 9
  • 61
  • 83
Yansh
  • 112
  • 2
  • 7
  • 1
    `obj.checkProp` is a property with the name of `checkProp`. it does not use the variable. – Nina Scholz Jul 02 '20 at 11:40
  • There are 2 ways to retrieve properties out from an object. 1.) Dot notation 2.) Bracket notation. The 1st one cannot be used to retrieve a proerty value with a dynamic property name. – Rajaprabhu Aravindasamy Jul 02 '20 at 11:41
  • @RajaprabhuAravindasamy can you elaborate on Dynamic Property name? I am new to JS so, I am not familiar with the terminology. – Yansh Jul 02 '20 at 11:47
  • @Yansh Dynamic property names are nothing but names that are resolved during runtime. In other words, if you try to retrieve a value from an object with a prop (key) that was stored in a variable. – Rajaprabhu Aravindasamy Jul 02 '20 at 11:48

0 Answers0