Chapter 5. Arrays

Since its inception, JavaScript has had arrays as a separate, standalone data type. But over the years, the way we interact with arrays has changed considerably.

In the past, manipulating an array involved plenty of loops and iterative logic, along with a small set of underpowered methods. Today, the Array object is stocked with much more functionality, including methods that emphasize functional approaches. Using these methods, you can filter, sort, copy, and transform data, without stepping through array elements one at a time.

In this chapter, you’ll see how to use these functional approaches—and learn when you might need to sidestep them. The focus is on solving problems using the most modern practices that are available today.

Caution

If you’re trying these examples out in the browser’s developer console, be warned that lazy evaluation can fool you. For example, consider what happens if you output an array with console.log(), sort it, and then log it again. You expect to see the information for two differently sorted arrays. But you’ll actually see the final, sorted array twice. That’s because most browsers won’t examine the items in your array until you open the console and click to expand the array. One way to avoid this problem is to iterate over the array and log each item separately. For more about the issue, see “Why Chrome’s Developer Console Sometimes Lies”.

Checking If an Object Is an Array

Problem

Before you perform an array ...

Get JavaScript Cookbook, 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.