Because prop is a variable name, not an actual property name. You can only use dot notation with property names.
{
id: 100
}
There is a property named id so you can get the value of the property by its name:
object.name
Using dot notation always means that the string to the right of the dot is an actual property name in the object. So when you try:
contacts[i].prop
JS is looking for a property named prop in the object.
Since prop is a variable that stores a property name, and that name is what you are really trying to find in the object, then you have to use bracket notation so JS knows that you want the value stored in prop.
contacts[i][prop]
This says to replace [prop] with the value stored in prop. So if prop is holding the string id then it would essentially become:
To add to this, for redability purposes it is far easier to tell what is going on in this snippet then using it mixed with a period. This is because periods can also represent function calls
just strictly readability and not functionality. It’s far cleaner to review code when it’s easy to skim over and see what is happening without extra effort
My general recommendation is to always use dot notation when the property being accessed will not change, which would include method calls. Bracket notation is for when the property you are accessing may change based on the way your code are functions are run.
Though, like many things, when there are different valid styles, you should defer to the prevailing style used by most developers or the prevailing style used by your team of collaborators.