Arrays represent a collection of values.
Each element of the collection can be independently changed.
[1, 2, 3, 'foo', true]
An array with five elements.
Values are enclosed in []
s and separated by commas.
[]
Same as with strings: []
.
const xs = [1, 2, 3, true, 'foo'];
xs[0] ⟹ 1
xs[1] ⟹ 2
xs[2] ⟹ 3
xs[3] ⟹ true
xs[4] ⟹ 'foo'
That we use []
s both in the syntax for making an array and in the index operator, is either unfortunate or mnemonic, depending on your point of view.
Assign to the first element of xs
.
xs[0] = 'x'
After the assignment:
xs[0]
⟹ 'x'
xs
⟹ ['x', 2, 3, true, 'foo']
I.e. the last element of the array
xs.push('another value')
xs ⟹ ['x', 2, 3, true, 'foo', 'another value']
push
is a method on arrays but unlike substring
, toLowerCase
, and toUpperCase
it modifies the value it is called on.
It also returns a value, namely the new length of the array.
xs.pop() ⟹ 'another value'
xs ⟹ ['x', 2, 3, true, 'foo']
pop
is another method on arrays. Like push
, it modifies the value it is called on and also returns a value, namely value being removed from the end of the array.
Create arrays: []
, [1, 2]
, ["foo", "bar, "baz"]
Access array elements: someArray[0]
, someArray[someArray.length - 1]
Assign array elements: someArray[0] = "oof"
Add to an array: someArray.push("quux")
You don’t need to know any of these except the ones I’ve taught you about but you may find some of them useful as you start writing more complicated programs.