Sub topic 1
Arrays in JavaScript: Creation, Indexing, and length
Prerequisites
This chapter assumes you know let and const, arrow functions, object property access, and basic for loops. You should be able to run code in Node.js or a browser console.
Creation, Indexing, and length
An array is an ordered list of values. You create one with square brackets. Indexes start at 0, and length is always one more than the highest index.
const fruits = ['apple', 'banana', 'cherry'];
console.log(fruits[0]); // 'apple'
console.log(fruits.length); // 3
fruits[1] = 'blueberry';
console.log(fruits); // ['apple', 'blueberry', 'cherry']A common mistake is reading fruits[3]. It returns undefined and does not throw an error.
Reading from the End with at()
fruits[-1] does not count from the end. It looks up a property named "-1", which does not exist. Use at() instead, because it accepts negative indexes:
const fruits = ['apple', 'banana', 'cherry'];
console.log(fruits.at(-1)); // 'cherry'
console.log(fruits[-1]); // undefinedDestructuring and Spreading Arrays
Destructuring assigns elements to variables by position. Spread syntax (...) copies elements into a new array.
const [first, ...rest] = ['a', 'b', 'c'];
console.log(first, rest); // 'a' ['b', 'c']
const copy = [...rest, 'd'];
console.log(copy); // ['b', 'c', 'd']Which Methods Change Your Array?
A mutating method changes the original array. A non-mutating method returns a new array. If you mix them up, you get bugs where data changes somewhere you didn't expect.
| Mutating | Non-mutating |
|---|---|
| `push`, `pop`, `shift`, `unshift`, `splice` | `slice`, `concat`, `map`, `filter` |
| `sort`, `reverse` | `toSorted`, `toReversed`, `with` |
Adding and Removing Elements
push and pop work at the end of the array. unshift and shift work at the start. splice(start, deleteCount, ...items) removes and inserts elements in place, and it returns the removed elements.
const letters = ['a', 'b', 'c', 'd'];
const removed = letters.splice(1, 2, 'x');
console.log(removed); // ['b', 'c']
console.log(letters); // ['a', 'x', 'd']
letters.push('e'); // returns new length 4
console.log(letters.pop()); // 'e'
letters.unshift('z');
console.log(letters.shift()); // 'z'Looping with for...of and forEach
for...of gives you each value, and you can stop early with break. forEach calls a function for every element. You cannot break out of it, and it returns undefined.
const nums = [10, 20, 30];
for (const [i, n] of nums.entries()) {
if (n > 20) break;
console.log(i, n); // 0 10, then 1 20
}
nums.forEach((n, i) => console.log(i, n));Exercise
After const a = [1, 2, 3, 4]; const b = a.splice(1, 1);, what are a, b, and a.at(-1)?
Show answer
a is [1, 3, 4] because splice mutates the array. b is [2] because splice returns the removed elements. a.at(-1) is 4.