Arrays 2

Basics

A variable can only hold one value. This is where arrays come in.

An array is like a variable but with square brackets and commer separated list of values.

const warWords = ['fight', 'bombs', 'spitfire', 'chimpanzee', 'melons']

Like variables, to use an array you simply drop the const or let and just write: warWords

uses the forEach() method to create an alert() for each item in the array.

function ww() {
    const warWords = ['fight', 'bombs', 'spitfire', 'chimpanzee', 'melons'];

    warWords.forEach(function (warWord) {
    alert(warWord);
    })
}

In the console this will give:

Array(5) [ "fight", "bombs", "spitfire", "chimpanzee", "melons" ]


Indexing

If we want just one of the values from the array we can select it based on it's position in the array. This is known as it's index. To select the third value we use a 2 (because JS starts counting with a zero) in square brackets.

warWords[2] returns "spitfire" to the console.

If you want to know the index of a known value you type: warWords.indexOf('bombs');

Arrays within arrays

Arrays can also hold arrays inside them:

const planes = [['cessna', 'apache', 'learjet'],['spitfire', 'hurricane', 'F16'],['Jumbo Jet', 'Boeing 757', 'Airbus']]

NOTE: each set of square brackets must still be separated by a comma.

To select an item the same square bracket notation is used to select the sub-array, then another square bracket is used to select the value within that array:

Typing planes[1][0] gives "spitfire", the first (0) value in the second(2) array.

Using .length to count from the last item

let floraSize = 'Trees are big';

floraSize.length; will tell you how long the variable is. In this case 13 letters and spaces.

floraSize[4]; will tell you what the fifth letter is: "s"

Now lets create an array with sub arrays and see what happens.

let flora = [['oak', 'beech', 'elm'], ['roses', 'dasies', 'tulips'], ['beechrow', 'orange', 'pear']];

So flora.length; will return 3 which is the number of arrays.

To access that last array: flora[flora.length -1]; will return the values of the last sub array: Array(3) [ "beechrow", "orange", "pear" ] which is the number of arrays.

To access that last array: flora[flora.length -1][0]; will return the values of the last sub array: "beechrow", the first value in the last array.

How do we change the values of an array?

pop(), push(), slice(), splice() and shift()

For example suppose we have an array:

const birds = ['sparrow', 'vulture', 'eagle', 'woodpecker', 'wren']

method What it does Example
pop removes last item birds.pop()
push adds to array push()
slice copies parts of an array to a new array slice()
splice removes and adds items anywhere in the array splce()
shift removes the first item on the array birds.shift()

Apart from slice the above methods to change or mutate the array values, even if the array is created with const.

myArray.pop() will remove the last item.