Tools for working with arrays

INPUT · Slides

Adding to the back of an array

01 / 05

You want to add more later

An array can grow after you have made it. Assign to a number that is not there yet, as in list[2] = "c", and the array gets longer.

But written that way, you end up counting how many are in there now yourself to decide the number. Miscount and it goes somewhere you did not mean.

02 / 05

push adds at the end

Write .push(value) after an array and it adds one at the very back. The nice part is that you do not decide the number.

An order like this .push(...), called on a value, is called a method. .length only took a value out as it was; a method is called with () on the end.

const fruits = ["apple", "orange"];fruits.push("peach");console.log(fruits);

Result

["apple", "orange", "peach"]

03 / 05

The length grows each time

You can call push as often as you like. It stacks on the back once per call.

As the items grow, .length grows with them. You do not have to manage the length yourself.

const nums = [10, 20];nums.push(30);nums.push(40);console.log(nums);console.log(nums.length);

Result

[10, 20, 30, 40]
4

04 / 05

Build up from an empty array

Where push comes alive most is building up from an empty array. Set up [] and add inside a loop.

The strength is that you can write it without knowing in advance how many there will be.

const squares = [];for (let i = 1; i <= 4; i++) {  squares.push(i * i);}console.log(squares);

Result

[1, 4, 9, 16]

05 / 05

Let us check it over

A tidy-up of what you have seen.

  • array.push(value) adds one at the back
  • .length grows by however many you added
  • you can build up from an empty array []

Right — try adding some.