Work with arrays, Maps, Sets, WeakMaps, and WeakSets. Learn when to use each and the built-in methods that make them powerful.
Why: arrays are ordered, zero-indexed collections. They come with a rich set of built-in methods for transformation, filtering, and searching.
const fruits = ['apple', 'banana', 'cherry'];
// Access & mutate
console.log(fruits[0]); // 'apple'
fruits.push('date'); // add to end
fruits.unshift('avocado'); // add to start
const removed = fruits.pop(); // remove from end
console.log(fruits);
// Iteration methods
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.map(n => n * 2));
console.log(numbers.filter(n => n % 2 === 0));
console.log(numbers.find(n => n > 3));
// Reduce
const sum = numbers.reduce((acc, n) => acc + n, 0);
console.log('sum:', sum);
// Spread & destructuring
const [first, second, ...rest] = fruits;
console.log(first, second, rest);Why: Map is like an object but allows any key type and preserves insertion order. WeakMap holds keys weakly (garbage-collectable) — useful for private data.
// Map — any key type, ordered
const map = new Map();
map.set('name', 'Alice');
map.set(42, 'the answer');
map.set(true, 'boolean key');
console.log(map.get('name')); // 'Alice'
console.log(map.get(42)); // 'the answer'
console.log(map.size); // 3
// Iterate
for (const [key, value] of map) {
console.log(key, '->', value);
}
// vs plain object: object keys are always strings/symbols
const obj = {};
obj[42] = 'coerced to string "42"';
console.log(Object.keys(obj)); // ['42']Why: Set stores unique values of any type. Ideal for deduplication and membership checks — has() is O(1) unlike array indexOf.
const set = new Set([1, 2, 3, 2, 1]);
console.log(set.size); // 3 — duplicates removed
console.log(set.has(2)); // true
set.add(4);
set.delete(1);
console.log([...set]); // [2, 3, 4]
// Deduplicate an array
const arr = [1, 2, 2, 3, 3, 4];
const unique = [...new Set(arr)];
console.log(unique); // [1, 2, 3, 4]
// Set operations (union)
const a = new Set([1, 2, 3]);
const b = new Set([2, 3, 4]);
const union = new Set([...a, ...b]);
console.log([...union]); // [1, 2, 3, 4]
const intersection = new Set([...a].filter(x => b.has(x)));
console.log([...intersection]); // [2, 3]