liveBook · Manning

Array

As explained in Secrets of the JavaScript Ninja, Third Edition

An array is an ordered JavaScript collection whose elements are accessed by numeric indexes.

An array is an ordered JavaScript collection accessed by numeric indexes. Unlike a fixed-size, single-type array in languages such as C, it can grow, shrink, and hold values of different types. It is also an object, which helps explain some surprising behavior. section 10.1

Create and index an array

const names = ["Kuma", "Hattori", "Yagyu"]; names[0] is "Kuma", and names.length is 3. Reading names[4] returns undefined rather than throwing an out-of-bounds error. Assigning names[4] = "Ishi" expands the array to length 5, leaving an empty position at index 3. Setting names.length = 2 instead truncates it. section 10.1.1

Prefer [] for ordinary creation. The Array constructor has a useful but unusual numeric case: new Array(5) creates an empty array of length 5, while new Array(5, 6) contains two numbers. Use fill when every position needs a value, as in new Array(100).fill("z"). The at(-1) method accesses the last item. section 10.1.1

Choose an operation according to where and how the collection should change:

  • push and pop add and remove at the end; unshift and shift do so at the beginning. Beginning-of-array changes can be costly for large arrays because later items may need to move. section 10.1.2
  • splice removes or inserts items at a chosen index and changes the original array. delete merely leaves an empty slot without shifting later items. section 10.1.3
  • slice returns a partial copy without changing the original; [...array] is a common way to copy an entire array. Do not confuse slice with splice. section 10.1.3

For traversal, use for…of when values matter or entries() when indexes matter. A for or for…of loop can exit early or await each iteration; forEach cannot break early or wait for an asynchronous callback before starting the next iteration. Avoid mistaking for…in, which visits keys and attached object properties, for value iteration. section 10.1.4

Callback methods express common collection jobs: map transforms each item into a new array; flatMap combines arrays produced from items; every and some test conditions; find returns the first match, while filter collects all matches. reduce combines items into one value. These methods often replace a loop and a manually managed result. section 10.1.4

Listing 10.5 Deriving an array with map
const ninjas = [
  { name: "Yagyu", weapon: "shuriken" },
  { name: "Yoshi", weapon: "katana" },
  { name: "Kuma", weapon: "wakizashi" },
];
 
const weapons = ninjas.map(({ weapon }) => weapon);  #A
console.assert(
  weapons[0] === "shuriken" &&
    weapons[1] === "katana" &&
    weapons[2] === "wakizashi",
  "Every ninja's weapon is included",
);

A short example shows map deriving an array of weapon names from an array of objects. section 10.1.4

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Works through creation, indexing, mutation, and callback methods, but defers typed arrays and their separate interfaces.
Examples
Uses indexed names, insertion and deletion, object-to-weapon mapping, condition checks, filtering, sorting, and numeric summation.
What it assumes
Builds on familiarity with C-like arrays and loops while explaining JavaScript-specific array behavior through examples.
What you can do after
Apply it via native JavaScript Array methods to change collections, derive new arrays, find items, and aggregate values.
How it connects
Connects arrays to objects, typed arrays, iterables, functional programming, and immutable collections.

Also explained in

Compare how 48 books explain array →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.