Data Structures#
JavaScript’s built-in collection types cover most everyday needs.
Arrays#
Ordered, zero-indexed, dynamically sized.
const xs = [1, 2, 3];
xs.push(4); // [1, 2, 3, 4]
xs.pop(); // 4
xs.unshift(0); // [0, 1, 2, 3]
const sub = xs.slice(1, 3);
const i = xs.indexOf(2);
const doubled = xs.map((x) => x * 2);
const evens = xs.filter((x) => x % 2 === 0);
const sum = xs.reduce((a, b) => a + b, 0);
Objects#
Hash maps with string or symbol keys.
const user = { name: "operator", age: 36 };
user.role = "admin";
delete user.age;
for (const [k, v] of Object.entries(user)) {
console.log(k, v);
}
const keys = Object.keys(user);
const merged = { ...user, active: true };
Map / Set#
When keys are non-string or insertion order matters, prefer Map over a
plain object. Set stores unique values.
const m = new Map();
m.set("a", 1).set("b", 2);
m.get("a"); // 1
m.has("c"); // false
m.size; // 2
const s = new Set([1, 2, 2, 3]);
s.add(4);
s.has(2); // true
[...s]; // [1, 2, 3, 4]
Tuples#
JavaScript has no first-class tuple type. The convention is to use a fixed-shape array, often with destructuring at the call site.
function divmod(a, b) {
return [Math.floor(a / b), a % b];
}
const [q, r] = divmod(17, 5);
Strings#
Immutable sequences of UTF-16 code units. They have many of the same methods as arrays.
const s = "hello world";
s.length; // 11
s.toUpperCase(); // "HELLO WORLD"
s.split(" "); // ["hello", "world"]
s.includes("world"); // true
s.replace("world", "operator");
Template literals interpolate expressions and span multiple lines.
const name = "operator";
const greeting = `hello,
${name}!`;
Typed Arrays#
For binary data and numeric workloads, use typed arrays.
const buf = new Uint8Array([72, 101, 108, 108, 111]);
const text = new TextDecoder().decode(buf); // "Hello"
WeakMap / WeakSet#
Like Map / Set, but keys must be objects and are held weakly: they
don’t prevent garbage collection. Useful for attaching metadata to objects
without leaking memory.