liveBook · Manning

Array

As explained in Secrets of the JavaScript Ninja, Second Edition

An ordered, indexed collection of values.

Arrays hold collections of items. In JavaScript, they are objects: this gives them access to methods, but can also have performance side effects. section 9.1

Creating and accessing arrays:

  • Prefer array literals ([]) to the Array constructor: they are simpler, and the built-in constructor could be overridden. section 9.1.1
  • Read values by index, starting at 0; length gives the array’s size. An out-of-range read returns undefined, while writing beyond the current end expands the array and can leave holes. section 9.1.1
Listing 9.1. Creating arrays
const ninjas = ["Kuma", "Hattori", "Yagyu"];                   #A
const samurai = new Array("Oda", "Tomoe");                     #B

assert(ninjas.length === 3, "There are three ninjas");         #C
assert(samurai.length === 2, "And only two samurai");          #C

assert(ninjas[0] === "Kuma", "Kuma is the first ninja");       #D
assert(samurai[samurai.length-1] === "Tomoe",                  #D
       "Tomoe is the last samurai");                           #D

assert(ninjas[4] === undefined,                                        #E
      "We get undefined if we try to access an out of bounds index");  #E

ninjas[4] = "Ishi";                                              #F
assert(ninjas.length === 5,                                      #F
      "Arrays are automatically expanded");                      #F

ninjas.length = 2;                                               #G
assert(ninjas.length === 2, "There are only two ninjas now");    #G
assert(ninjas[0] === "Kuma" && ninjas[1] === "Hattori",          #G
       "Kuma and Hattori");                                      #G
assert(ninjas[2] === undefined, "But we've lost Yagyu");         #G

See literal and constructor forms, indexed reads, and an assignment that expands an array. section 9.1.1

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains creation, indexing, length, and out-of-range behavior without descending into implementation internals.
Examples
Uses arrays of ninjas and samurai to demonstrate creation, indexed access, and out-of-range reads.
What you can do after
Build it from scratch by creating arrays, reading indexed values, and extending them with assignments.
How it connects
Connects arrays to JavaScript objects, array methods, maps, and sets.

Also explained in

Compare how 40 books explain array →

Related concepts

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