Arrays and their methods

An array is an ordered list of values in square brackets:

const snacks = ["crisps", "grapes", "toast"];

Each item has a position called an index, and indexes start at 0, not 1. So snacks[0] is "crisps" and snacks[2] is "toast". Yes, counting from zero feels wrong at first. Everyone gets over it eventually.

snacks.length tells you how many items there are (3). The last item is always at snacks[snacks.length - 1].

Arrays come with built-in tools called methods, which you call with a dot:

  • snacks.push("pizza") adds an item to the end
  • snacks.pop() removes the last item and returns it
  • snacks.includes("toast") gives true or false

Note that push works on a const array. const stops you pointing the name at a different array; it does not stop you changing what is inside this one.

To visit every item, a for...of loop is the cleanest:

for (const snack of snacks) {
  console.log(snack);
}

map and filter

These two take a function and build a new array, leaving the original alone:

const nums = [1, 2, 3, 4];
const doubled = nums.map((n) => n * 2);       // [2, 4, 6, 8]
const evens = nums.filter((n) => n % 2 === 0); // [2, 4]

map runs your function on every item and collects the results. filter keeps only the items where your function returns true. You pass in a function, so all that arrow function practice pays off right here.

Try it yourself

Edit it. Break it. Run it again.
const snacks = ["crisps", "grapes", "toast"];
console.log(snacks[0], snacks.length);

snacks.push("pizza");
console.log(snacks);

for (const snack of snacks) {
  console.log(`I like ${snack}`);
}

const nums = [1, 2, 3, 4];
console.log(nums.map((n) => n * 2));
console.log(nums.filter((n) => n % 2 === 0));
console.log(nums);
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

Your turn

Type it yourself. That is the whole trick.

1Add to the queue

Use push to add "Zoe" to the end of queue, then print the array and then its length.

const queue = ["Ali", "Ben"];
console.log(queue);
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

2Map and filter

Using scores, create two new arrays: passed, holding only the scores of 50 or more (use filter), and bonus, holding every score plus 5 (use map).

const scores = [72, 45, 90, 30, 55];
const passed = scores;
const bonus = scores;
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

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.