O'Reilly logo

Learning JavaScript, 3rd Edition by Ethan Brown

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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. So don’t ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required