JavaScript Destructuring & Spread Cheatsheet
javascriptDestructuring, spread, rest, and optional chaining reference.
Array Destructuring
const [a, b] = arrayExtract array elements into individual variables by position
const [x, y] = [1, 2];
// x = 1, y = 2const [a, , b] = arrayUse empty slots to skip unwanted array elements
const [first, , third] = [1, 2, 3];
// first = 1, third = 3const [a = defaultA, b = defaultB] = arrayAssign fallback values when array element is undefined
const [a = 5, b = 10] = [1];
// a = 1, b = 10const [first, ...rest] = arrayCollect remaining elements into a new array
const [head, ...tail] = [1, 2, 3, 4];
// head = 1, tail = [2, 3, 4][a, b] = [b, a]Exchange variable values without a temporary variable
let a = 1, b = 2;
[a, b] = [b, a];
// a = 2, b = 1const [a, b] = functionReturningArray()Destructure arrays returned from functions directly
const [min, max] = [1, 2, 3].reduce(
([mn, mx], v) => [Math.min(mn, v), Math.max(mx, v)],
[Infinity, -Infinity]
);Object Destructuring
const { prop1, prop2 } = objectExtract object properties into variables with matching names
const { name, age } = { name: 'Alice', age: 30 };
// name = 'Alice', age = 30const { prop: newName } = objectExtract property and assign it to a differently named variable
const { name: userName } = { name: 'Bob' };
// userName = 'Bob'const { prop = defaultValue } = objectProvide fallback when property is undefined
const { role = 'guest' } = { name: 'Eve' };
// role = 'guest'const { prop: newName = defaultValue } = objectCombine renaming and default value assignment
const { status: code = 200 } = {};
// code = 200const { prop1, ...rest } = objectCollect remaining properties into a new object
const { id, ...data } = { id: 1, name: 'Test', val: 42 };
// id = 1, data = { name: 'Test', val: 42 }const { [expression]: variable } = objectDestructure using dynamic property names
const key = 'color';
const { [key]: value } = { color: 'blue' };
// value = 'blue'function fn({ prop1, prop2 }) { }Destructure objects directly in function parameters
function greet({ name, age = 18 }) {
return `${name} is ${age}`;
}
greet({ name: 'Sam' });Nested Destructuring
const { outer: { inner } } = objectExtract values from deeply nested object properties
const { user: { profile: { name } } } = {
user: { profile: { name: 'Zoe' } }
};
// name = 'Zoe'const [[a, b], [c, d]] = nestedArrayExtract values from arrays within arrays
const [[a, b], [c]] = [[1, 2], [3, 4]];
// a = 1, b = 2, c = 3const { prop: [a, b] } = objectCombine object and array destructuring for complex structures
const { coords: [x, y] } = { coords: [10, 20] };
// x = 10, y = 20const { outer: { inner = default } = {} } = objectApply defaults at multiple nesting levels to prevent errors
const { config: { theme = 'dark' } = {} } = {};
// theme = 'dark'const { items: [first, ...remaining] } = objectUse rest syntax within nested array destructuring
const { tags: [primary, ...others] } = {
tags: ['js', 'web', 'dev']
};
// primary = 'js', others = ['web', 'dev']Spread Operator
[...array1, ...array2]Expand array elements into a new array
const merged = [...[1, 2], ...[3, 4]];
// [1, 2, 3, 4]const copy = [...original]Create a shallow copy of an array
const original = [1, 2, 3];
const copy = [...original];{ ...obj1, ...obj2 }Merge objects or create shallow copies with property spread
const merged = { ...{ a: 1 }, ...{ b: 2 } };
// { a: 1, b: 2 }{ ...obj, prop: newValue }Copy object and override specific properties
const updated = { ...user, name: 'New' };
// Copies user, overrides namefn(...args)Expand array as individual function arguments
const nums = [1, 5, 3];
Math.max(...nums); // 5array1.push(...array2)Add multiple elements to array using spread
const arr = [1, 2];
arr.push(...[3, 4]);
// arr = [1, 2, 3, 4][...string]Split string into array of characters
const chars = [...'hello'];
// ['h', 'e', 'l', 'l', 'o']{ ...obj, ...(condition && { prop: val }) }Conditionally include properties in object spread
const obj = {
name: 'Test',
...(true && { active: true })
};Rest Parameters
function fn(a, b, ...rest) { }Collect remaining arguments into an array
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3); // 6function fn(first, second, ...others) { }Combine named parameters with rest for remaining arguments
function log(level, ...messages) {
messages.forEach(m => console.log(`[${level}] ${m}`));
}(...args) => expressionUse rest parameters in arrow function syntax
const multiply = (...nums) => nums.reduce((a, b) => a * b, 1);
multiply(2, 3, 4); // 24function fn(a, ...rest, b) // SyntaxErrorRest parameter must always be the final parameter
// WRONG: function fn(...rest, last) {}
// RIGHT: function fn(first, ...rest) {}function fn(...args) { } // Use instead of argumentsRest params create real array unlike arguments object
function demo(...args) {
return args.filter(x => x > 0); // Works!
}Optional Chaining
obj?.propSafely access property returning undefined if obj is nullish
const user = null;
user?.name; // undefined (no error)obj?.prop1?.prop2Chain multiple optional accesses for deep properties
const data = { user: null };
data?.user?.profile?.name; // undefinedarr?.[index]Safely access array elements with bracket notation
const arr = null;
arr?.[0]; // undefinedobj?.method?.()Safely call method that may not exist
const api = {};
api.fetch?.(); // undefined (no error)obj?.[expression]Optional chaining with computed property names
const key = 'name';
const obj = null;
obj?.[key]; // undefineddelete obj?.propSafely delete property that may not exist
const obj = null;
delete obj?.name; // No error, returns trueNullish Coalescing
value ?? defaultValueReturn right side only if left is null or undefined
null ?? 'default'; // 'default'
0 ?? 'default'; // 0value || default vs value ?? defaultUnlike OR nullish coalescing preserves falsy values like 0 and empty string
0 || 10; // 10
0 ?? 10; // 0
'' || 'hi'; // 'hi'
'' ?? 'hi'; // ''a ?? b ?? cChain multiple fallbacks for sequential null checks
const val = null ?? undefined ?? 'found';
// 'found'obj?.prop ?? defaultCombine optional chaining with fallback value
const config = null;
const theme = config?.theme ?? 'light';
// 'light'a ?? b || c // SyntaxError without parensMust use parentheses when combining with AND or OR operators
// Wrong: a ?? b || c
// Right: (a ?? b) || c
// Right: a ?? (b || c)Logical Assignment Operators
x ||= yAssign y to x only if x is falsy
let a = '';
a ||= 'default';
// a = 'default'x &&= yAssign y to x only if x is truthy
let obj = { name: 'test' };
obj &&= { ...obj, updated: true };
// obj = { name: 'test', updated: true }x ??= yAssign y to x only if x is null or undefined
let count = 0;
count ??= 10;
// count = 0 (preserved!)obj.prop ??= valueSet object property only if currently nullish
const user = { name: 'Ann' };
user.role ??= 'guest';
// user.role = 'guest'x ??= expensiveOperation()Right side only evaluates if assignment will occur
let cached = getData();
cached ??= fetchFromAPI(); // Only calls API if cached is nullishobj.arr ??= []Ensure array or object exists before pushing or adding
const data = {};
data.items ??= [];
data.items.push('new');