{ ILoveJS }

JavaScript Destructuring & Spread Cheatsheet

javascript

Destructuring, spread, rest, and optional chaining reference.

8 sections · 48 items

Array Destructuring

Basic Array Destructuring
const [a, b] = array

Extract array elements into individual variables by position

typescript
const [x, y] = [1, 2];
// x = 1, y = 2
Skip Elements
const [a, , b] = array

Use empty slots to skip unwanted array elements

typescript
const [first, , third] = [1, 2, 3];
// first = 1, third = 3
Default Values
const [a = defaultA, b = defaultB] = array

Assign fallback values when array element is undefined

typescript
const [a = 5, b = 10] = [1];
// a = 1, b = 10
Rest in Array Destructuring
const [first, ...rest] = array

Collect remaining elements into a new array

typescript
const [head, ...tail] = [1, 2, 3, 4];
// head = 1, tail = [2, 3, 4]
Swap Variables
[a, b] = [b, a]

Exchange variable values without a temporary variable

typescript
let a = 1, b = 2;
[a, b] = [b, a];
// a = 2, b = 1
Function Return Destructuring
const [a, b] = functionReturningArray()

Destructure arrays returned from functions directly

typescript
const [min, max] = [1, 2, 3].reduce(
  ([mn, mx], v) => [Math.min(mn, v), Math.max(mx, v)],
  [Infinity, -Infinity]
);

Object Destructuring

Basic Object Destructuring
const { prop1, prop2 } = object

Extract object properties into variables with matching names

typescript
const { name, age } = { name: 'Alice', age: 30 };
// name = 'Alice', age = 30
Renaming Variables
const { prop: newName } = object

Extract property and assign it to a differently named variable

typescript
const { name: userName } = { name: 'Bob' };
// userName = 'Bob'
Default Values
const { prop = defaultValue } = object

Provide fallback when property is undefined

typescript
const { role = 'guest' } = { name: 'Eve' };
// role = 'guest'
Rename with Default
const { prop: newName = defaultValue } = object

Combine renaming and default value assignment

typescript
const { status: code = 200 } = {};
// code = 200
Rest in Object Destructuring
const { prop1, ...rest } = object

Collect remaining properties into a new object

typescript
const { id, ...data } = { id: 1, name: 'Test', val: 42 };
// id = 1, data = { name: 'Test', val: 42 }
Computed Property Names
const { [expression]: variable } = object

Destructure using dynamic property names

typescript
const key = 'color';
const { [key]: value } = { color: 'blue' };
// value = 'blue'
Function Parameter Destructuring
function fn({ prop1, prop2 }) { }

Destructure objects directly in function parameters

typescript
function greet({ name, age = 18 }) {
  return `${name} is ${age}`;
}
greet({ name: 'Sam' });

Nested Destructuring

Nested Object Destructuring
const { outer: { inner } } = object

Extract values from deeply nested object properties

typescript
const { user: { profile: { name } } } = {
  user: { profile: { name: 'Zoe' } }
};
// name = 'Zoe'
Nested Array Destructuring
const [[a, b], [c, d]] = nestedArray

Extract values from arrays within arrays

typescript
const [[a, b], [c]] = [[1, 2], [3, 4]];
// a = 1, b = 2, c = 3
Mixed Nested Destructuring
const { prop: [a, b] } = object

Combine object and array destructuring for complex structures

typescript
const { coords: [x, y] } = { coords: [10, 20] };
// x = 10, y = 20
Nested with Defaults
const { outer: { inner = default } = {} } = object

Apply defaults at multiple nesting levels to prevent errors

typescript
const { config: { theme = 'dark' } = {} } = {};
// theme = 'dark'
Array in Object with Rest
const { items: [first, ...remaining] } = object

Use rest syntax within nested array destructuring

typescript
const { tags: [primary, ...others] } = {
  tags: ['js', 'web', 'dev']
};
// primary = 'js', others = ['web', 'dev']

Spread Operator

Spread in Array Literals
[...array1, ...array2]

Expand array elements into a new array

typescript
const merged = [...[1, 2], ...[3, 4]];
// [1, 2, 3, 4]
Copy Array
const copy = [...original]

Create a shallow copy of an array

typescript
const original = [1, 2, 3];
const copy = [...original];
Spread in Object Literals
{ ...obj1, ...obj2 }

Merge objects or create shallow copies with property spread

typescript
const merged = { ...{ a: 1 }, ...{ b: 2 } };
// { a: 1, b: 2 }
Override Object Properties
{ ...obj, prop: newValue }

Copy object and override specific properties

typescript
const updated = { ...user, name: 'New' };
// Copies user, overrides name
Spread in Function Calls
fn(...args)

Expand array as individual function arguments

typescript
const nums = [1, 5, 3];
Math.max(...nums); // 5
Spread with Push
array1.push(...array2)

Add multiple elements to array using spread

typescript
const arr = [1, 2];
arr.push(...[3, 4]);
// arr = [1, 2, 3, 4]
String to Array
[...string]

Split string into array of characters

typescript
const chars = [...'hello'];
// ['h', 'e', 'l', 'l', 'o']
Conditional Spread
{ ...obj, ...(condition && { prop: val }) }

Conditionally include properties in object spread

typescript
const obj = {
  name: 'Test',
  ...(true && { active: true })
};

Rest Parameters

Rest Parameters in Functions
function fn(a, b, ...rest) { }

Collect remaining arguments into an array

typescript
function sum(...nums) {
  return nums.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3); // 6
Rest with Named Parameters
function fn(first, second, ...others) { }

Combine named parameters with rest for remaining arguments

typescript
function log(level, ...messages) {
  messages.forEach(m => console.log(`[${level}] ${m}`));
}
Rest in Arrow Functions
(...args) => expression

Use rest parameters in arrow function syntax

typescript
const multiply = (...nums) => nums.reduce((a, b) => a * b, 1);
multiply(2, 3, 4); // 24
Rest Must Be Last
function fn(a, ...rest, b) // SyntaxError

Rest parameter must always be the final parameter

typescript
// WRONG: function fn(...rest, last) {}
// RIGHT: function fn(first, ...rest) {}
Rest vs Arguments
function fn(...args) { } // Use instead of arguments

Rest params create real array unlike arguments object

typescript
function demo(...args) {
  return args.filter(x => x > 0); // Works!
}

Optional Chaining

Property Access
obj?.prop

Safely access property returning undefined if obj is nullish

typescript
const user = null;
user?.name; // undefined (no error)
Nested Property Access
obj?.prop1?.prop2

Chain multiple optional accesses for deep properties

typescript
const data = { user: null };
data?.user?.profile?.name; // undefined
Array Element Access
arr?.[index]

Safely access array elements with bracket notation

typescript
const arr = null;
arr?.[0]; // undefined
Function Call
obj?.method?.()

Safely call method that may not exist

typescript
const api = {};
api.fetch?.(); // undefined (no error)
Dynamic Property Access
obj?.[expression]

Optional chaining with computed property names

typescript
const key = 'name';
const obj = null;
obj?.[key]; // undefined
With Delete
delete obj?.prop

Safely delete property that may not exist

typescript
const obj = null;
delete obj?.name; // No error, returns true

Nullish Coalescing

Basic Nullish Coalescing
value ?? defaultValue

Return right side only if left is null or undefined

typescript
null ?? 'default'; // 'default'
0 ?? 'default'; // 0
vs Logical OR
value || default vs value ?? default

Unlike OR nullish coalescing preserves falsy values like 0 and empty string

typescript
0 || 10; // 10
0 ?? 10; // 0
'' || 'hi'; // 'hi'
'' ?? 'hi'; // ''
Chained Nullish Coalescing
a ?? b ?? c

Chain multiple fallbacks for sequential null checks

typescript
const val = null ?? undefined ?? 'found';
// 'found'
With Optional Chaining
obj?.prop ?? default

Combine optional chaining with fallback value

typescript
const config = null;
const theme = config?.theme ?? 'light';
// 'light'
Cannot Mix with AND/OR
a ?? b || c // SyntaxError without parens

Must use parentheses when combining with AND or OR operators

typescript
// Wrong: a ?? b || c
// Right: (a ?? b) || c
// Right: a ?? (b || c)

Logical Assignment Operators

Logical OR Assignment
x ||= y

Assign y to x only if x is falsy

typescript
let a = '';
a ||= 'default';
// a = 'default'
Logical AND Assignment
x &&= y

Assign y to x only if x is truthy

typescript
let obj = { name: 'test' };
obj &&= { ...obj, updated: true };
// obj = { name: 'test', updated: true }
Nullish Assignment
x ??= y

Assign y to x only if x is null or undefined

typescript
let count = 0;
count ??= 10;
// count = 0 (preserved!)
Object Property Assignment
obj.prop ??= value

Set object property only if currently nullish

typescript
const user = { name: 'Ann' };
user.role ??= 'guest';
// user.role = 'guest'
Short-circuit Behavior
x ??= expensiveOperation()

Right side only evaluates if assignment will occur

typescript
let cached = getData();
cached ??= fetchFromAPI(); // Only calls API if cached is nullish
Initialize Nested Property
obj.arr ??= []

Ensure array or object exists before pushing or adding

typescript
const data = {};
data.items ??= [];
data.items.push('new');

Related Content