JavaScript Collections
Arrays, Objects & Map / Set
JavaScript's built-in data structures — the ones you'll reach for in nearly every function you write.
ES2023
✓ Core Concepts
4 Topics
01
Arrays
Arrays are ordered, resizable, and can hold mixed types. The methods you use most — map, filter, reduce — never mutate the original array; they return a new one.
JavaScript — Array Methods
const nums = [1, 2, 3, 4, 5]; nums.push(6); // mutates — adds to end nums.pop(); // mutates — removes last const doubled = nums.map(n => n * 2); // [2,4,6,8,10] — new array const evens = nums.filter(n => n % 2 === 0); // [2,4] — new array const total = nums.reduce((sum, n) => sum + n, 0); // 15 nums.find(n => n > 3); // 4 — first match nums.includes(3); // true nums.some(n => n > 4); // true — at least one nums.every(n => n > 0); // true — all match
Array.isArray(x) is the reliable check —
typeof [1,2,3] returns "object", not "array".02
Objects
Objects are key-value pairs, JavaScript's version of a dictionary/hash map. Keys are always strings or Symbols internally, even when they look like numbers.
JavaScript — Object Basics
const user = { name: "Ada", age: 36 }; user.email = "ada@x.com"; // add a property delete user.age; // remove a property Object.keys(user); // ["name", "email"] Object.values(user); // ["Ada", "ada@x.com"] Object.entries(user); // [["name","Ada"], ["email","ada@x.com"]] // shallow clone / merge const merged = { ...user, role: "admin" }; Object.freeze(user); // now truly immutable
03
Destructuring & Spread
Destructuring unpacks values out of arrays or objects in one line. Spread does the reverse — expands an iterable into individual elements.
JavaScript — Destructuring & Spread/Rest
// Array destructuring const [first, second, ...rest] = [10, 20, 30, 40]; // first=10 second=20 rest=[30,40] // Object destructuring — with rename & default const { name, age: years = 18 } = { name: "Ada" }; // name="Ada" years=18 (default, key was missing) // Spread — merge arrays / clone / function args const combined = [...[1,2], ...[3,4]]; // [1,2,3,4] function sum(...nums) { return nums.reduce((a,b) => a+b); } sum(1, 2, 3); // rest params — gathers args into an array
Same
... syntax, opposite jobs: on the left of an assignment it's rest (gathers); on the right or in a call it's spread (expands).04
Map & Set
A plain object works fine for string keys, but Map allows any key type and preserves insertion order reliably. Set stores unique values only — the standard tool for de-duplication.
JavaScript — Map & Set
const scores = new Map(); scores.set("ada", 95); scores.set("grace", 88); scores.get("ada"); // 95 scores.has("linus"); // false scores.size; // 2 const unique = new Set([1, 2, 2, 3, 3]); [...unique]; // [1, 2, 3] — duplicates gone unique.add(4); unique.has(2); // true
✓
Quick Quiz
1. Which array method never mutates the original?
2. typeof [1,2,3] returns…
3. const [a, ...b] = [1,2,3] — what is b?
4. Set is best for…
5. Object.freeze(obj) prevents…