Destructuring, Spread/Rest & Modern Syntax
18 min read
DestructuringSpread OperatorRest ParametersOptional ChainingNullish CoalescingTemplate LiteralsMap Set WeakMap
ES6+ Destructuring
Object Destructuring
const user = { name: "Alice", age: 30, role: "admin" };
// Basic
const { name, age } = user;
// Rename
const { name: userName } = user;
// Default values
const { country = "US" } = user;
// Nested
const response = { data: { users: [{ id: 1 }] } };
const { data: { users: [{ id }] } } = response; // id = 1
// Rest
const { role, ...rest } = user; // rest = { name: "Alice", age: 30 }Array Destructuring
const [first, second, ...remaining] = [1, 2, 3, 4, 5];
// first = 1, second = 2, remaining = [3, 4, 5]
// Skip elements
const [, , third] = [1, 2, 3]; // third = 3
// Swap variables (no temp needed!)
let a = 1, b = 2;
[a, b] = [b, a]; // a = 2, b = 1Spread Operator (...)
// Arrays
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]
// Objects (shallow copy)
const original = { a: 1, b: { c: 2 } };
const copy = { ...original, a: 99 }; // Override `a`
copy.b.c = 999; // ⚠️ Mutates original.b.c too! (shallow copy)
// Function arguments
Math.max(...[1, 2, 3]); // 3Optional Chaining (?.) & Nullish Coalescing (??)
const user = { profile: { address: null } };
// Optional Chaining
user.profile?.address?.city; // undefined (no error)
user.settings?.theme; // undefined (no error)
user.getProfile?.(); // undefined (safe method call)
users?.[0]?.name; // undefined (safe array access)
// Nullish Coalescing
const port = config.port ?? 3000;
// Only uses 3000 if port is null or undefined
// NOT for 0 or "" (unlike ||)
// Comparison:
0 || 3000; // 3000 (0 is falsy)
0 ?? 3000; // 0 (0 is NOT null/undefined)Template Literals & Tagged Templates
// Basic
const greeting = `Hello, ${name}!`;
// Multi-line
const html = `
<div class="card">
<h2>${title}</h2>
</div>
`;
// Tagged Templates (for sanitization, i18n, CSS-in-JS)
function highlight(strings, ...values) {
return strings.reduce((result, str, i) => {
return result + str + (values[i] ? `<mark>${values[i]}</mark>` : "");
}, "");
}
const name = "Alice";
highlight`Hello ${name}, welcome!`;
// "Hello <mark>Alice</mark>, welcome!"Map, Set, WeakMap, WeakSet
| Structure | Keys | Iterable | GC-Friendly | Use Case |
|---|---|---|---|---|
Map | Any type | Yes | No | Key-value store with non-string keys |
Set | N/A (values) | Yes | No | Unique collections |
WeakMap | Objects only | No | Yes | Private data, caching |
WeakSet | N/A (objects) | No | Yes | Tracking visited objects |