Arrays
An array is a data structure that contains any number of items (or elements
). In JavaScript, array elements can be of any data type.
Create an empty array:
const arr = []
Elements in the array should be separated by commas.
const satchel = [
'chair',
'table',
'candle',
'map',
'magnifying glass',
'rupees',
'Quick Eze',
'boomerang'
]
const squares = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Accessing Elements
Each element in the array has a numbered index
. The first element has an index of 0
.
Access elements by putting the index number
in square brackets.
const satchel = [
'chair',
'table',
'candle',
'map',
'magnifying glass',
'rupees',
'Quick Eze',
'boomerang'
]
console.log(satchel[0]) // => 'chair'
console.log(satchel[1]) // => 'table'
Getting the Number of Elements in an Array
We can use the .length
property to find out the number of elements in an array
const satchel = [
'chair',
'table',
'candle',
'map',
'magnifying glass',
'rupees',
'Quick Eze',
'boomerang'
]
console.log(satchel.length) // => 8
Changing Elements
To change an element in an array, first access the element, and then assign a new value:
const satchel = [
'chair',
'table',
'candle',
'map',
'magnifying glass',
'rupees',
'Quick Eze',
'boomerang'
]
satchel[2] = 'glowing orb'
console.log(satchel)
NOTE: const
only prevents reassignment, the value can still be mutated.
Iterate over an array
Let's use a for..of
loop to iterate over the array and print each element out.
for (let item of satchel) {
console.log(`A nimble rogue is trying to steal my ${item}!!!1`)
}
Last updated
Was this helpful?