2

The syntax in JavaScript for accessing the property of an object is:

object.property or object["property"] or object[property]

I was trying out this lesson on freeCodeCamp:

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

function checkObj(checkProp) {
  if( myObj.hasOwnProperty(checkProp) )
    return myObj[checkProp];

  return "Not Found";
}

checkObj("gift");

... the console displays the expected prop with object[property] syntax and undefined otherwise. Why is this?

andres
  • 301
  • 6
  • 21

2 Answers2

3

Because only object[property] lets you to use a dynamic property (kept in a variable, in your particular case - checkProp).

The others - object.property or object["property"] refer directly to a prop named property, and since there isn't such prop as property, you'll receive undefined.

kind user
  • 40,029
  • 7
  • 67
  • 77
1

Since property is a variable, to access the object property dynamically you must have to use Bracket ([]) notation. Otherwise it will always give you undefined.

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

function checkObj(checkProp) {
  if( myObj.hasOwnProperty(checkProp) )
    return myObj[checkProp];

  return "Not Found";
}

console.log(checkObj("gift"));
console.log(checkObj("g"));
Giulio Bambini
  • 4,695
  • 4
  • 21
  • 36