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 8. Arrays and Array Processing

JavaScript’s array methods are among my favorite features of the language. So many programming problems involve the manipulation of collections of data, and fluency with JavaScript’s array methods will make that easy. Getting comfortable with these methods is also a great way to attain the next level of JavaScript mastery.

A Review of Arrays

Before we dive in, let’s remind ourselves of the basics of arrays. Arrays (unlike objects) are inherently ordered, with zero-based numeric indices. Arrays in JavaScript can be nonhomogeneous, meaning the elements in an array do not need to be the same type (it follows from this that arrays can have other arrays as elements, or objects). Literal arrays are constructed with square brackets, and the same square brackets are used to access elements by index. Every array has a length property, which tells you how many elements are in the array. Assigning to an index that’s larger than the array will automatically make the array larger, with unused indexes getting the value undefined. You can also use the Array constructor to create arrays, though this is seldom necessary. Make sure all of the following makes sense to you before you proceed:

// array literals
const arr1 = [1, 2, 3];                              // array of numbers
const arr2 = ["one", 2, "three"];                    // nonhomogeneous array
const arr3 = [[1, 2, 3], ["one", 2, "three"]];       // array containing arrays
const arr4 = [                                       // nonhomogeneous array
   { name: "Fred", type: "object", luckyNumbers ...

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