Getting started with arrays
Terminology
- Array literal
- A comma separated list of values surrounded by
[]
. For example, ['cats', 'dogs', 'fish']. - Array index
- The location of an item in an array. In Javascript, his is always a sequential number starting at 0.
- Array item
- Any Javascript data type (i.e. value) that an array index points to.
- Array length
- The number of items in an array. Accessed with the
Array.length
property.
Key Takeaways
-
Creating an array using
const
still allows you to change (or mutate) the items in that array.const hobbies = ['pinball', 'bug hunting', 'napping'];
hobbies[2] = 'proper sleeping'; // No error!const
only stops you from re-assigninghobbies
, not changinghobbies
.
-
The value of an element can be any data type:
undefined
,null
,number
,string
,boolean
,array
,object
, etc.const randomStuff = [null, 9, 'Hello World!'];
- Although it's possible, you rarely see a mix of different value types in the same array.
Accessing array items
Given the following array:
const animals = [
'Puppy',
'Bear',
'Moose',
'Coyote',
'Tiger',
'Husky'
];
-
You can retrieve an item from an array using the index:
const thirdAnimal = animals[2]; // Moose
-
The first index of an array is always
0
.const firstAnimal = animals[0]; // Puppy
-
The last index of an array is always
Array.length - 1
.const lastAnimal = animals[animals.length - 1]; // Husky
-
To add an item to an array, the next index is always
array.length
.animals[animals.length] = 'Wolf'; // New item at the end of the array