An array is an ordered collection.
const nums = [1, 2, 3];
const mixed = ["a", 1, true, null, { x: 1 }];
console.log(nums.length); // 3
console.log(nums[0]); // 1Key points:
- Arrays are objects (
typeof [] === "object"). - Indexes are 0-based.
lengthis mutable.
const a = [1, 2, 3];
a.length = 1;
console.log(a); // [1]Common mutating vs non-mutating methods:
- Non-mutating:
slice,concat,map,filter,reduce,toSorted(newer) - Mutating:
push,pop,shift,unshift,splice,sort,reverse
const a = [1, 2, 3];
const b = a.slice(0, 2);
console.log(a, b); // [1,2,3] [1,2]
a.splice(1, 1);
console.log(a); // [1,3]Default sort() converts to strings, which can be surprising.
const n = [2, 10, 1];
n.sort();
console.log(n); // [1,10,2] (string compare)Use a compare function for numeric sorting.
const n = [2, 10, 1];
n.sort((a, b) => a - b);
console.log(n); // [1,2,10]Custom sorting objects:
const users = [
{ name: "A", age: 30 },
{ name: "B", age: 20 },
];
users.sort((u1, u2) => u1.age - u2.age);for...ofiterates values (recommended for arrays).for...initerates enumerable keys (indexes) and can include unexpected properties.
const a = ["x", "y"];
for (const v of a) console.log(v); // x, y
for (const k in a) console.log(k); // 0, 1Transform each element, returns a new array.
const a = [1, 2, 3];
const doubled = a.map((x) => x * 2);
console.log(doubled); // [2,4,6]Select elements by predicate.
const a = [1, 2, 3, 4];
const even = a.filter((x) => x % 2 === 0);
console.log(even); // [2,4]Fold an array into a single value.
const a = [1, 2, 3];
const sum = a.reduce((acc, x) => acc + x, 0);
console.log(sum); // 6Build objects with reduce:
const words = ["a", "b", "a"];
const counts = words.reduce((acc, w) => {
acc[w] = (acc[w] ?? 0) + 1;
return acc;
}, {});
console.log(counts); // { a: 2, b: 1 }Use for side effects. It does not return a new array.
const a = [1, 2, 3];
a.forEach((x) => {
console.log("value:", x);
});Prefer map/filter/reduce when you want returned values.