Arrays
Arrays are ordered lists of values. They can contain any type of data.
Creating Arrays
const fruits = ['apple', 'banana', 'cherry']
const mixed = [1, 'hello', true, null, { x: 1 }]
const empty = []
Accessing Elements
fruits[0] // 'apple' (zero-indexed)
fruits[fruits.length - 1] // 'cherry' (last element)
fruits.at(-1) // 'cherry' (ES2022)
Modifying Arrays
fruits.push('date') // add to end
fruits.pop() // remove from end
fruits.unshift('avocado')// add to beginning
fruits.shift() // remove from beginning
fruits.splice(1, 1) // remove 1 element at index 1
Useful Methods
const nums = [3, 1, 4, 1, 5, 9, 2, 6]
nums.length // 8
nums.includes(5) // true
nums.indexOf(1) // 1 (first occurrence)
nums.sort() // [1, 1, 2, 3, 4, 5, 6, 9]
nums.reverse() // [9, 6, 5, 4, 3, 2, 1, 1]
nums.join(', ') // '9, 6, 5, 4, 3, 2, 1, 1'
nums.slice(0, 3) // [9, 6, 5] (non-destructive)
for...of with Arrays
for (const fruit of fruits) {
console.log(fruit)
}