liveBook · Manning

Array

As explained in JavaScript in Depth

An indexed collection data structure that stores multiple values in an ordered sequence.

An array is a specialized object whose numeric indices support ordered values, automatic length tracking, and methods inherited from Array.prototype. Its coercion behavior can hide costly work: converting an array to a number first converts it to a string. section 5.11 section 4.4.4

The coercion puzzle

Number([1]) produces 1 because String([1]) produces "1". Number([1, 2]) produces NaN because String([1, 2]) produces "1,2", which cannot be parsed as a number. With thousands of elements, constructing the intermediate string iterates through the array and creates substantial avoidable work. section 4.4.4

Use these rules when reasoning about arrays:

  • Treat numeric indexing, length tracking, and inherited array methods as specialized behavior layered onto object semantics. section 5.11
  • Inspect implicit conversions in comparisons, numeric operations, and loops; repeated coercion can dominate runtime work. section 4.4.4
console.log(Number([1]));  // 1
console.log(Number([1,2]));  // NaN

Run the contrasting coercion examples to observe why a one-element array becomes a number while a two-element array becomes NaN. section 4.4.4

How JavaScript in Depth covers it

How deep it goes
Traces array-to-string-to-number conversion and specialized object behavior, but stops short of full runtime implementation details.
Examples
Uses Number([1]), Number([1,2]), and Number(Array(10_000)) to expose conversion results and scaling costs.
What it assumes
Assumes JavaScript expressions and numbers while deriving array conversion behavior from basic string coercion.
What you can do after
Diagnose implicit array coercion and recognize when intermediate string construction creates avoidable performance costs.
How it connects
Connects arrays to objects, type coercion, numeric conversion, prototypes, and performance.

Also explained in

Compare how 48 books explain array →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of JavaScript in Depth. The section links point to the parts of the book it draws on.