In Unit 3, you learned about JavaScript primitive data types such as strings, numbers, and Booleans. In addition, this unit introduces the "array" and "object" data types.
Why use objects?
We've seen a few suspicious-looking expressions like myString.length
(to get the length of a string) and Math.max
(the maximum function) in past chapters. These are expressions that access a property of some value. In the first case, we access the length
property of the value in myString
. In the second, we access the property named max
in the Math
object (which is a collection of mathematics-related constants and functions).
Almost all JavaScript values have properties. The exceptions are null
and undefined
. If you try to access a property on one of these nonvalues, you get an error.
null.length; // → TypeError: null has no properties
The two main ways to access properties in JavaScript are with a dot and with square brackets. Both value.x
and value[x]
access a property on value – but not necessarily the same property. The difference is in how x
is interpreted. When using a dot, the
word after the dot is the literal name of the property. When using square brackets, the expression between the brackets is evaluated to get the property name. Whereas value.x
fetches the property of value
named "x", value[x]
tries to evaluate the
expression x and uses the result, converted to a string, as the property name.
So if you know that the property you are interested in is called color, you say value.color
. If you want to extract the property named by the value held in the binding i, you say value[i]
. Property names are strings. They can be any string, but the dot
notation works only with names that look like valid binding names. So if you want to access a property named 2 or John Doe, you must use square brackets: value[2]
or value["John Doe"]
.
The elements in an array are stored as the array's properties, using numbers as property names. Because you can't use the dot notation with numbers and usually want to use a binding that holds the index anyway, you have to use the bracket notation to get at them.
The length
property of an array tells us how many elements it has. This property name is a valid binding name, and we know its name in advance, so to find the length of an array, you typically write array.length
because that's easier to write than array["length"]
.