0

I don't understand how using record.prop is different than using record[prop] inside functions when they give the same output outside functions, as shown below:

var ourDog = {
   "name": "Camper"
};
ourDog.bark = "bow-wow";

function update(record, prop) {
  record.prop = "cannot";
  record[prop] = "woof";
  return record;
}

console.log(update(ourDog, "anotherbark"));

Basically when I use dot instead of brackets, the property doesn't change to anotherbark but instead remainds as prop as shown in the result below:

{
   "name": "Camper",
   "bark": "bow-wow",
   "prop": "cannot",
   "anotherbark": "woof"
}
t2fmkh
  • 77
  • 8
  • 1
    Does this answer your question? [JavaScript property access: dot notation vs. brackets?](https://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets) – LW001 Sep 03 '21 at 16:02
  • `record.prop` accesses the field called `prop`, not `record.anotherbark` (the value of the `prop` parameter). `record[prop]` access the field `record.anotherbark` which is why you are getting two new fields in your object when you call `update`. – D M Sep 03 '21 at 16:10
  • Why don't you understand the difference. You know that `ourDog.bark` creates a property named `bark`. Why would `record.prop` be any different? – Barmar Sep 03 '21 at 16:13
  • @Barmar I think the reason why I didn't understand it was because ourDog.bark and ourDog["bark"] would have given the same output, but inside the function record[prop] and record.prop didn't give the same output... but I think I get it now so it's all good! – t2fmkh Sep 03 '21 at 17:57
  • Notice the difference in quotes. `record.prop` is equivalent to `record["prop"]`, not `record[prop]`. – Barmar Sep 03 '21 at 18:25

0 Answers0