Brainlag
  1. Library
  2. Concepts
  3. Web

Arrays

An array keeps values in order. Read them by index from 0, add with push, count with length and walk through them with for...of.

Web10 min

Indexes start at 0

An array is a list of values in order, inside square brackets. Each one sits at a numbered position called an index, and counting starts at 0.

JavaScript
const queue = ["Ana", "Ben", "Cleo"];
queue[0]                  // "Ana"
queue[2]                  // "Cleo"
queue.length              // 3
queue[queue.length - 1]   // "Cleo", the last one
queue[3]                  // undefined: nothing there

The last index is always length - 1. Asking past the end does not crash, it just gives undefined.

Adding and looping

push adds to the end and changes the array, even one made with const (the name still points at the same array; only its contents change).

JavaScript
queue.push("Dev");

To do something with every item, for...of hands you each value in turn:

JavaScript
for (const name of queue) {
  console.log(name + " is in the lobby");
}

Need the position too? Use a counting loop: for (let i = 0; i < queue.length; i++). Note <, not <=.

Run it: a playlist

Run it, then change one thing and run it again.

main.js to run
const playlist = ["Neon Rain", "Late Bus", "Stone Road"];
playlist.push("Paper Planes");

console.log("Songs:", playlist.length);
console.log("First:", playlist[0]);
console.log("Last:", playlist[playlist.length - 1]);

for (let i = 0; i < playlist.length; i++) {
  console.log(i + 1 + ". " + playlist[i]);
}

Add the last round

kills holds a player's kills in each round. A late round just finished with 7 kills: add it to the end of the array. Then print how many rounds there were and the total kills, exactly like this:

Output
Rounds: 5
Total: 30

Use a loop for the total, not a number you worked out yourself.

Constraint

  • Add up the kills with a loop.
  • Add the new round with push.
exercise_1.js to run
const kills = [5, 9, 3, 6];

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.