-2

learn javascript from freecodecamp, when i reach object, they teach about bracket notation and dot notation, when i use dot notation in return obj.checkProp like below 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
}

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

the return is undefied but when i use bracket notation in return obj[checkProp]

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
}

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

it return kitten. my question is why the dot is not working but the bracket is working

andruw oei
  • 39
  • 5
  • 2
    Haven't you demonstrated the difference with your example? – jonrsharpe Nov 19 '20 at 13:27
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors – Teemu Nov 19 '20 at 13:30
  • 1
    because `checkProp` isn't a property of `obj`, but contains it's name. `obj.pet` is equivalent to `obj['pet']`. This is exactly the same than `var foo = 'bar'; console.log(foo);` it displays `'bar'`, not `'foo'` – Cid Nov 19 '20 at 13:31

1 Answers1

1

The reason is that you want to check for the value contained in the variable checkProp rather than for the value checkProp.

obj[checkProp] is equivalent to obj.pet in your example whereas obj.checkProp is equivalent to obj['checkProp']

user650881
  • 2,214
  • 19
  • 31