Chapter 9. Objects and Object-Oriented Programming

We covered the basics of objects in Chapter 3, 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 properties 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 implementations may change at any time for reasons of efficiency. ...

Get Learning JavaScript, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.