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







































