JS record collection challenge - why must i use [] to access object properties?

Comparing my code against the solution code it’s almost identical. Only difference is the way i use . as well as [] to access object properties. Why does it work with ‘[]’ only but not ‘.’ ?

function updateRecords(id, prop, value) {
  if (prop === "tracks" && value !== "") {
    if (collection.id.hasOwnProperty[prop]) {
      collection.id[prop].push(value);
    } else {
      collection.id[prop] = [value];
    }
  } else if (value !== "") {
    collection.id[prop] = value;
  } else {
    delete collection.id[prop];
  }
  return collection;
}

The error message i get in console is:

Cannot set property ‘artist’ of undefined.

Because if you are not using [], interpreter (computer) will not know that you want it to use your variable value instead of property with name of “id”.
In other words, when you access object property like this:
someObject.someProperty;
it will look for property with name “someProperty”, not value of variable named someProperty.
With . you tell interpreter exact name of the property, but with [] you can pass it variable that stores that name.
With syntax you are trying to use, there is no way to know if you are trying to access property named “id” or you accessing property with name that is stored in variable id.
Computer can not guess things like that, it just follows the rules, thus the rule to use [] in situations like that.

Edit: Imagine for example if it worked the way you want it to work. It would mean that for example to use method “hasOwnProperty” or other methods you are using you would need to do this:

let methodName = "hasOwnProperty";
object.methodName(something);
methodName = "someOtherMethod";
object.methodName();

Compare that to how it actually works:

object.hasOwnProperty(something);
object.someOtherMethod();

It is clear that second way to do it is way more convenient.
And when you actually need to take name from variable you can just use [].

3 Likes

I see, thanks so much for your reply!