Arrays and objects
Arrays
Goal: Create, read and modify arrays · 9 min
An array is an ordered list: const nums = [3, 1, 4]; Index from 0: nums[0]; last element: nums.at(-1) or nums[nums.length - 1].
Mutating methods: push (add at end), pop (remove last), unshift/shift (front), splice, sort, reverse. Non-mutating: slice, concat, includes, indexOf, join, spread [...a, ...b].
A const array can still be changed internally — const only forbids assigning a new array to the name.
Caution: sort() sorts as strings by default: [10, 9, 1].sort() → [1, 10, 9]. For numbers: sort((a, b) => a - b).
Worked example: Numeric sort
- Default sort compares "10" < "9" as text.
- The compare function a − b sorts numerically.
- Output shows both.
console.log([10, 9, 1].sort().join(","));
console.log([10, 9, 1].sort((a, b) => a - b).join(","));Output:
1,10,9
1,9,10