CHAPTER 9
Objects and Object-Oriented Programming
We covered the basics of objects in
, but now it’s time to take a deeper look
at objects in JavaScript.
Like arrays, objects in JavaScript are containers (also called aggregate or complex data
types). Objects have two primary differences from arrays:
• Arrays contain values, indexed numerically; objects contain properties, indexed
by string or symbol.
• Arrays are ordered (
arr[0]
always comes before
arr[1]
); objects are not (you
can’t guarantee
obj.a
comes before
obj.b
).
These differences are pretty esoteric (but important), so let’s think about the property
(no pun intended) that makes objects really special. A property consists of a key (a
string or symbol) and a value. What makes objects special is that you can access prop‐
erties by their key.
Property Enumeration
In general, if you want to list out the contents of the container (called enumeration),
you probably want an array, not an object. But objects are containers, and do support
property enumeration; you just need to be aware of the special complexities involved.
The first thing you need to remember about property enumeration is that order isn’t
guaranteed. You might do some testing and find that you get properties out in the
order in which you put them in, and that may be true for many implementations most
of the time. However, JavaScript explicitly offers no guarantee on this, and implemen‐
tations may change at any time for reasons of efficiency. So don’t be lulled into a false
147