While utilizing alternatives such as the dot operator make sense when needing to access some stored information, I'm having a little bit of difficulty understanding why and in what scenarios we would use variables to accomplish the same task.
For example:
var myObj = {
prop1: "val1",
prop2: "val2"
};
var prop1val = myObj.prop1; // val1
var prop2val = myObj.prop2; // val2
versus:
var testObj = {
12: "Namath",
16: "Montana",
19: "Unitas"
};
var playerNumber = 16;
var player = testObj[playerNumber];
Is it simply a matter of preference, or are there actual benefits to using each?
One thing that distinguishes them is that with dot notation, you have to already know the property you want to access.
Consider the instance where you may want to obtain user input or some other external factor to decide what property to obtain:
In the above function, one could not write
return data.property
- it would look for a property calledproperty
! You'd have to use index notation to get the correct value.It is usually based on preference, however I like to use bracket notation for arrays, and dot notation for objects. However if there is a property on the object with a dash in it, only bracket notation can be used.
Bracket syntax allows you to dynamically access property names, whereas dot syntax does not. Here is an example of how it could be used:
Bracket syntax also allows you the ability to use object properties that are otherwise invalid variable names (which is not recommended, but is doable).
For example:
The subscript syntax is more flexible than dot notation in a few ways. In your own example, performing some of the following operations is clearly impossible:
The dot notation is limited in that it cannot be used with variables holding dynamic values.
testObj.playerNumber
is not at all the same astestObj[playerNumber]
.Bracket syntax is dynamic- It is typically used for collections, such as Lists, Arrays, Dictionaries, et cetera. Period notation is more useful for non-iterable fields, methods, and everything else you might want to access from a class.
For instance, you could iterate over a list with