JavaScript 24 🧬 Destructuring
Destructuring assignment is a feature that allows you to extract data from arrays or objects into variables. It uses syntax that looks similar to array or object literal notation, making your code more concise and readable.
A Quick Look at the Examples
// 1. Array destructuring
const [a, b, c] = [1, 2, 3];
console.log(a, b, c); // 1 2 3
// 2. Skipping elements
const [x, , y] = [4, 5, 6];
console.log(x, y); // 4 6
// 3. Default values
const [p, q = 10] = [7];
console.log(p, q); // 7 10
// 4. Object destructuring
const { name, age } = { name: 'Alice', age: 25 };
console.log(name, age); // Alice 25
// 5. Renaming and defaults
const { firstName: fn, lastName: ln, middleName = 'M' } = { firstName: 'John', lastName: 'Doe' };
console.log(fn, ln, middleName); // John Doe M
// 6. Nested destructuring
const user = {
id: 1,
name2: 'Jane',
address: {
city: 'New York',
zip: '10001'
}
};
const { name2, address: { city, zip } } = user;
console.log(name2, city, zip); // Jane New York 10001
// 7. Function parameter destructuring
function displayInfo({ name, age }) {
console.log(`Name: ${name}, Age: ${age}`);
}
displayInfo({ name: 'Bob', age: 30 }); // Name: Bob, Age: 30
a. Introduction and Array Destructuring
Destructuring assignment allows you to extract data from arrays or objects into variables. It uses syntax that looks similar to array or object literal notation, making your code more concise and readable.
Array Destructuring
const [a, b, c] = [1, 2, 3];
// a = 1, b = 2, c = 3
How it works: Values from the array are assigned to variables in order.
Skipping Elements
Use a comma with no variable to skip an element.
const [x, , y] = [4, 5, 6];
// x = 4, y = 6 (5 is skipped)
Visual:
[4, 5, 6]
│ │ │
│ ✗ │
▼ ▼
x y
Default Values
Provide defaults with = in case the array is shorter.
const [p, q = 10] = [7];
// p = 7, q = 10 (default used since array has only one value)
const [a = 1, b = 2] = [];
// a = 1, b = 2 (both defaults)
const [c = 1, d = 2] = [99];
// c = 99, d = 2 (first overridden, second default)
Note: Defaults are only used when the value is undefined — not when it’s null.
const [a = 5] = [null];
console.log(a); // null (default not used)
Swapping Variables
Array destructuring makes swapping elegant:
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a, b); // 2 1
Without destructuring:
let temp = a;
a = b;
b = temp;
Rest in Array Destructuring
Combine with rest to collect remaining items:
const [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]
b. Object Destructuring
Object destructuring extracts properties into variables by name.
const { name, age } = { name: 'Alice', age: 25 };
// name = 'Alice', age = 25
Key difference from arrays: Order doesn’t matter — properties are matched by name.
Renaming Variables
Use : to assign a property to a different variable name.
const { firstName: fn, lastName: ln } = { firstName: 'John', lastName: 'Doe' };
console.log(fn); // "John"
console.log(ln); // "Doe"
Syntax: { originalName: newName }
Default Values
Combine renaming with defaults:
const { firstName: fn, middleName = 'M' } = { firstName: 'John' };
console.log(fn); // "John"
console.log(middleName); // "M"
Full example:
const { firstName: fn, lastName: ln, middleName = 'M' } = { firstName: 'John', lastName: 'Doe' };
console.log(fn, ln, middleName); // John Doe M
Nested Destructuring
Extract deeply nested properties:
const user = {
id: 1,
name: 'Jane',
address: {
city: 'New York',
zip: '10001'
}
};
const { name, address: { city, zip } } = user;
console.log(name); // "Jane"
console.log(city); // "New York"
console.log(zip); // "10001"
Note: The nested object (address) is not created as a variable — only its properties are.
// This would throw an error:
// console.log(address); // ReferenceError
// To also get the address object:
const { name, address, address: { city, zip } } = user;
console.log(address); // { city: 'New York', zip: '10001' }
Function Parameter Destructuring
Destructure directly in function parameters — especially useful in React:
function displayInfo({ name, age }) {
console.log(`Name: ${name}, Age: ${age}`);
}
displayInfo({ name: 'Bob', age: 30 }); // Name: Bob, Age: 30
With defaults:
function greet({ name = 'Guest', greeting = 'Hello' } = {}) {
return `${greeting}, ${name}!`;
}
greet({ name: 'Alice' }); // "Hello, Alice!"
greet({}); // "Hello, Guest!"
greet(); // "Hello, Guest!" (empty object default)
Rest in Object Destructuring
Collect remaining properties:
const { a, b, ...others } = { a: 1, b: 2, c: 3, d: 4 };
console.log(a); // 1
console.log(b); // 2
console.log(others); // { c: 3, d: 4 }
Practical use — omit sensitive fields:
const user = { id: 1, name: 'Alice', password: 'secret', role: 'admin' };
const { password, ...safeUser } = user;
console.log(safeUser); // { id: 1, name: 'Alice', role: 'admin' }
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Destructuring</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background: #f8f9fa;
color: #333;
line-height: 1.6;
}
h1 { color: #007bff; border-bottom: 3px solid #007bff; padding-bottom: 10px; }
h2 { color: #28a745; border-left: 4px solid #28a745; padding-left: 15px; margin-top: 30px; }
.demo-box {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
margin: 15px 0;
}
pre {
background: #1e1e1e;
color: #d4d4d4;
padding: 15px;
border-radius: 8px;
overflow-x: auto;
font-family: 'Courier New', monospace;
font-size: 0.9rem;
line-height: 1.8;
}
.keyword { color: #569cd6; }
.string { color: #ce9178; }
.number { color: #b5cea8; }
.function { color: #dcdcaa; }
.comment { color: #6a9955; }
.boolean { color: #569cd6; }
#output {
background: #e9ecef;
padding: 15px;
border-radius: 8px;
margin-top: 15px;
min-height: 40px;
font-family: 'Courier New', monospace;
font-size: 0.85rem;
border-left: 4px solid #007bff;
white-space: pre-wrap;
}
table {
width: 100%;
border-collapse: collapse;
margin: 15px 0;
}
th, td {
padding: 10px;
border: 1px solid #ddd;
text-align: left;
}
th { background: #007bff; color: white; }
tr:nth-child(even) { background: #f8f9fa; }
.btn {
padding: 10px 20px;
background: #007bff;
color: white;
border: none;
border-radius: 6px;
font-size: 1em;
font-weight: bold;
cursor: pointer;
margin: 5px;
transition: all 0.3s;
}
.btn:hover {
background: #0056b3;
transform: translateY(-2px);
}
.btn-success { background: #28a745; }
.btn-success:hover { background: #1e7e34; }
.result-display {
font-family: 'Courier New', monospace;
font-size: 1.1em;
color: #007bff;
background: #f8f9fa;
padding: 15px;
border-radius: 8px;
margin: 10px 0;
border-left: 4px solid #007bff;
white-space: pre-wrap;
}
</style>
</head>
<body>
<h1>Destructuring</h1>
<div class="demo-box">
<h2>1. Array Destructuring</h2>
<pre>
<span class="keyword">const</span> [a, b, c] = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];
console.log(a, b, c); <span class="comment">// 1 2 3</span>
<span class="keyword">const</span> [x, , y] = [<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>];
console.log(x, y); <span class="comment">// 4 6 (5 skipped)</span>
<span class="keyword">const</span> [p, q = <span class="number">10</span>] = [<span class="number">7</span>];
console.log(p, q); <span class="comment">// 7 10 (default used)</span>
</pre>
</div>
<div class="demo-box">
<h2>2. Object Destructuring</h2>
<pre>
<span class="keyword">const</span> { name, age } = { name: <span class="string">'Alice'</span>, age: <span class="number">25</span> };
console.log(name, age); <span class="comment">// Alice 25</span>
<span class="comment">// Renaming and defaults</span>
<span class="keyword">const</span> { firstName: fn, lastName: ln, middleName = <span class="string">'M'</span> }
= { firstName: <span class="string">'John'</span>, lastName: <span class="string">'Doe'</span> };
console.log(fn, ln, middleName); <span class="comment">// John Doe M</span>
</pre>
</div>
<div class="demo-box">
<h2>3. Nested Destructuring</h2>
<pre>
<span class="keyword">const</span> user = {
id: <span class="number">1</span>,
name: <span class="string">'Jane'</span>,
address: {
city: <span class="string">'New York'</span>,
zip: <span class="string">'10001'</span>
}
};
<span class="keyword">const</span> { name, address: { city, zip } } = user;
console.log(name, city, zip); <span class="comment">// Jane New York 10001</span>
</pre>
</div>
<div class="demo-box">
<h2>4. Function Parameter Destructuring</h2>
<pre>
<span class="keyword">function</span> <span class="function">displayInfo</span>({ name, age }) {
console.log(<span class="string">`Name: ${name}, Age: ${age}`</span>);
}
<span class="function">displayInfo</span>({ name: <span class="string">'Bob'</span>, age: <span class="number">30</span> });
<span class="comment">// Name: Bob, Age: 30</span>
</pre>
</div>
<div class="demo-box">
<h2>5. Interactive: Destructuring Playground</h2>
<div class="result-display" id="resultDisplay">Click a button to see destructuring in action</div>
<div style="margin: 10px 0;">
<button class="btn" onclick="demoArray()">Array Destructure</button>
<button class="btn" onclick="demoSkip()">Skip Element</button>
<button class="btn btn-success" onclick="demoDefaults()">Defaults</button>
<button class="btn" onclick="demoSwap()">Swap Variables</button>
<button class="btn" onclick="demoObject()">Object Destructure</button>
<button class="btn" onclick="demoRename()">Rename + Default</button>
<button class="btn" onclick="demoNested()">Nested</button>
<button class="btn btn-success" onclick="demoRest()">Rest Pattern</button>
<button class="btn" onclick="demoOmit()">Omit Sensitive</button>
</div>
</div>
<div class="demo-box">
<h2>6. Destructuring Cheat Sheet</h2>
<table>
<tr>
<th>Pattern</th>
<th>Syntax</th>
<th>Result</th>
</tr>
<tr>
<td><strong>Array basic</strong></td>
<td><code>const [a, b] = [1, 2]</code></td>
<td><code>a=1, b=2</code></td>
</tr>
<tr>
<td><strong>Skip element</strong></td>
<td><code>const [a, , c] = [1, 2, 3]</code></td>
<td><code>a=1, c=3</code></td>
</tr>
<tr>
<td><strong>Default value</strong></td>
<td><code>const [a = 5] = []</code></td>
<td><code>a=5</code></td>
</tr>
<tr>
<td><strong>Swap</strong></td>
<td><code>[a, b] = [b, a]</code></td>
<td>Swaps a and b</td>
</tr>
<tr>
<td><strong>Object basic</strong></td>
<td><code>const { x, y } = { x: 1, y: 2 }</code></td>
<td><code>x=1, y=2</code></td>
</tr>
<tr>
<td><strong>Rename</strong></td>
<td><code>const { x: newX } = { x: 1 }</code></td>
<td><code>newX=1</code></td>
</tr>
<tr>
<td><strong>Default</strong></td>
<td><code>const { x = 5 } = {}</code></td>
<td><code>x=5</code></td>
</tr>
<tr>
<td><strong>Nested</strong></td>
<td><code>const { a: { b } } = { a: { b: 1 } }</code></td>
<td><code>b=1</code></td>
</tr>
<tr>
<td><strong>Rest</strong></td>
<td><code>const { a, ...rest } = { a: 1, b: 2 }</code></td>
<td><code>rest={b: 2}</code></td>
</tr>
<tr>
<td><strong>Parameter</strong></td>
<td><code>function fn({ a, b }) { }</code></td>
<td>Destructures arg</td>
</tr>
</table>
</div>
<div class="demo-box">
<h2>7. Live Output — All Examples</h2>
<div id="output">Loading...</div>
</div>
<script>
// ============================================
// Destructuring — Live Demo
// ============================================
let results = [];
// 1. Array destructuring
results.push('📌 Array Destructuring:\n');
const [a, b, c] = [1, 2, 3];
results.push(' const [a, b, c] = [1, 2, 3]');
results.push(' → a=' + a + ', b=' + b + ', c=' + c);
results.push('');
// 2. Skipping elements
results.push('📌 Skipping Elements:\n');
const [x, , y] = [4, 5, 6];
results.push(' const [x, , y] = [4, 5, 6]');
results.push(' → x=' + x + ', y=' + y + ' (5 skipped)');
results.push('');
// 3. Default values
results.push('📌 Default Values:\n');
const [p, q = 10] = [7];
results.push(' const [p, q = 10] = [7]');
results.push(' → p=' + p + ', q=' + q);
results.push('');
// 4. Swapping
results.push('📌 Swapping Variables:\n');
let s1 = 'first', s2 = 'second';
results.push(' Before: s1=' + s1 + ', s2=' + s2);
[s1, s2] = [s2, s1];
results.push(' After: s1=' + s1 + ', s2=' + s2);
results.push('');
// 5. Object destructuring
results.push('📌 Object Destructuring:\n');
const { name, age } = { name: 'Alice', age: 25 };
results.push(' const { name, age } = { name: "Alice", age: 25 }');
results.push(' → name=' + name + ', age=' + age);
results.push('');
// 6. Renaming and defaults
results.push('📌 Renaming and Defaults:\n');
const { firstName: fn, lastName: ln, middleName = 'M' } = { firstName: 'John', lastName: 'Doe' };
results.push(' const { firstName: fn, lastName: ln, middleName = "M" } =');
results.push(' { firstName: "John", lastName: "Doe" }');
results.push(' → fn=' + fn + ', ln=' + ln + ', middleName=' + middleName);
results.push('');
// 7. Nested destructuring
results.push('📌 Nested Destructuring:\n');
const user = {
id: 1,
name: 'Jane',
address: {
city: 'New York',
zip: '10001'
}
};
const { name: userName, address: { city, zip } } = user;
results.push(' const user = { name: "Jane", address: { city: "NY", zip: "10001" } }');
results.push(' const { name: userName, address: { city, zip } } = user');
results.push(' → userName=' + userName + ', city=' + city + ', zip=' + zip);
results.push('');
// 8. Function parameter destructuring
results.push('📌 Function Parameter Destructuring:\n');
function displayInfo({ name, age }) {
return `Name: ${name}, Age: ${age}`;
}
results.push(' function displayInfo({ name, age }) { }');
results.push(' displayInfo({ name: "Bob", age: 30 })');
results.push(' → ' + displayInfo({ name: 'Bob', age: 30 }));
results.push('');
// 9. Rest in destructuring
results.push('📌 Rest Pattern:\n');
const [first, second, ...restArr] = [1, 2, 3, 4, 5];
results.push(' const [first, second, ...restArr] = [1, 2, 3, 4, 5]');
results.push(' → first=' + first + ', second=' + second + ', restArr=[' + restArr.join(', ') + ']');
results.push('');
const { a: aVal, b: bVal, ...others } = { a: 1, b: 2, c: 3, d: 4 };
results.push(' const { a: aVal, b: bVal, ...others } = { a: 1, b: 2, c: 3, d: 4 }');
results.push(' → aVal=' + aVal + ', bVal=' + bVal + ', others=' + JSON.stringify(others));
results.push('');
// 10. Omitting sensitive fields
results.push('📌 Omitting Sensitive Fields:\n');
const fullUser = { id: 1, name: 'Alice', password: 'secret', role: 'admin' };
const { password, ...safeUser } = fullUser;
results.push(' const user = { id: 1, name: "Alice", password: "secret", role: "admin" }');
results.push(' const { password, ...safeUser } = user');
results.push(' → safeUser=' + JSON.stringify(safeUser));
results.push('');
// 11. Practical: React-style props
results.push('📌 Practical: React-Style Props:\n');
function UserCard({ name, age, role = 'User' }) {
return `${name} (${age}) — ${role}`;
}
results.push(' function UserCard({ name, age, role = "User" }) { }');
results.push(' UserCard({ name: "Alice", age: 30, role: "Admin" })');
results.push(' → ' + UserCard({ name: 'Alice', age: 30, role: 'Admin' }));
results.push('');
// 12. Practical: swap with function
results.push('📌 Practical: Array of Objects:\n');
const users = [
{ id: 1, name: 'Alice', role: 'Admin' },
{ id: 2, name: 'Bob', role: 'User' },
{ id: 3, name: 'Carol', role: 'Editor' }
];
users.forEach(({ id, name, role }) => {
results.push(' #' + id + ' ' + name + ' (' + role + ')');
});
document.getElementById('output').textContent = results.join('\n');
// ============================================
// Interactive Demos
// ============================================
const resultDisplay = document.getElementById('resultDisplay');
function demoArray() {
const [a, b, c] = [1, 2, 3];
resultDisplay.textContent = `[a, b, c] = [1, 2, 3]\n→ a=${a}, b=${b}, c=${c}`;
}
function demoSkip() {
const [x, , y] = [4, 5, 6];
resultDisplay.textContent = `[x, , y] = [4, 5, 6]\n→ x=${x}, y=${y}\n(5 is skipped)`;
}
function demoDefaults() {
const [p, q = 10] = [7];
resultDisplay.textContent = `[p, q = 10] = [7]\n→ p=${p}, q=${q}\n(q uses default since array has only 1 value)`;
}
function demoSwap() {
let a = 'first', b = 'second';
const before = `a=${a}, b=${b}`;
[a, b] = [b, a];
resultDisplay.textContent = `Before: ${before}\nAfter: a=${a}, b=${b}`;
}
function demoObject() {
const { name, age } = { name: 'Alice', age: 25 };
resultDisplay.textContent = `{ name, age } = { name: 'Alice', age: 25 }\n→ name=${name}, age=${age}`;
}
function demoRename() {
const { firstName: fn, lastName: ln, middleName = 'M' } =
{ firstName: 'John', lastName: 'Doe' };
resultDisplay.textContent =
`{ firstName: fn, lastName: ln, middleName = 'M' }\n` +
`= { firstName: 'John', lastName: 'Doe' }\n` +
`→ fn=${fn}, ln=${ln}, middleName=${middleName}`;
}
function demoNested() {
const user = {
name: 'Jane',
address: { city: 'New York', zip: '10001' }
};
const { name, address: { city, zip } } = user;
resultDisplay.textContent =
`{ name, address: { city, zip } } = user\n` +
`→ name=${name}, city=${city}, zip=${zip}`;
}
function demoRest() {
const [first, second, ...rest] = [1, 2, 3, 4, 5];
const { a, b, ...others } = { a: 1, b: 2, c: 3, d: 4 };
resultDisplay.textContent =
`Array: [first, second, ...rest] = [1, 2, 3, 4, 5]\n` +
`→ first=${first}, second=${second}, rest=[${rest.join(', ')}]\n\n` +
`Object: { a, b, ...others } = { a: 1, b: 2, c: 3, d: 4 }\n` +
`→ a=${a}, b=${b}, others=${JSON.stringify(others)}`;
}
function demoOmit() {
const user = { id: 1, name: 'Alice', password: 'secret', role: 'admin' };
const { password, ...safeUser } = user;
resultDisplay.textContent =
`const user = { id: 1, name: 'Alice', password: 'secret', role: 'admin' }\n` +
`const { password, ...safeUser } = user\n\n` +
`safeUser = ${JSON.stringify(safeUser, null, 2)}`;
}
</script>
</body>
</html>
Quick Reference
Array Destructuring
| Pattern | Syntax | Result |
|---|---|---|
| Basic | const [a, b] = [1, 2] | a=1, b=2 |
| Skip | const [a, , c] = [1, 2, 3] | a=1, c=3 |
| Default | const [a = 5] = [] | a=5 |
| Rest | const [a, ...rest] = [1, 2, 3] | a=1, rest=[2, 3] |
| Swap | [a, b] = [b, a] | Swaps values |
Object Destructuring
| Pattern | Syntax | Result |
|---|---|---|
| Basic | const { x, y } = { x: 1, y: 2 } | x=1, y=2 |
| Rename | const { x: newX } = { x: 1 } | newX=1 |
| Default | const { x = 5 } = {} | x=5 |
| Rename + Default | const { x: newX = 5 } = {} | newX=5 |
| Nested | const { a: { b } } = { a: { b: 1 } } | b=1 |
| Rest | const { a, ...rest } = { a: 1, b: 2 } | rest={b: 2} |
Where to Use Destructuring
| Context | Example |
|---|---|
| Variable declaration | const { name } = user; |
| Function parameters | function fn({ name, age }) { } |
| Array methods | arr.map(({ id, name }) => ...) |
| Swap | [a, b] = [b, a] |
| Return values | const [min, max] = getMinMax(); |
| Omit fields | const { password, ...safe } = user; |
Best Practices
✅ Do This:
// Destructure in function parameters
function greet({ name, age }) {
console.log(`${name} is ${age}`);
}
// Use defaults in destructuring
function config({ port = 3000, host = 'localhost' } = {}) { }
// Omit sensitive fields with rest
const { password, ...safeUser } = user;
// Use renaming for clarity
const { name: userName, age: userAge } = user;
// Use array destructuring for swaps
[a, b] = [b, a];
// Use destructuring in array methods
users.map(({ id, name }) => ({ id, name }));
// Provide default object for parameter destructuring
function fn({ a, b } = {}) { }
❌ Don’t Do This:
// Don't forget the default object for optional params
function fn({ a, b }) { } // ❌ Throws if no argument!
fn(); // TypeError: Cannot destructure property 'a' of undefined
// Don't use destructuring with undefined values
const { a } = undefined; // ❌ TypeError
// Don't over-destructure (keep it readable)
const { a: { b: { c: { d: { e } } } } } = obj; // ❌ Too deep
// Don't shadow outer variables
const name = 'outer';
const { name } = obj; // ⚠️ Shadows outer `name`
// Don't use destructuring when direct access is clearer
const { length } = arr; // Fine, but arr.length is clearer
Common Pitfalls
| Pitfall | Problem | Solution |
|---|---|---|
Destructuring null/undefined | TypeError | Use default object = {} |
| Default not applied | Value is null, not undefined | Defaults only for undefined |
| Rest param not last | SyntaxError | Move ...rest to the end |
| Shallow copy trap | Nested objects shared | Use deep clone if needed |
| Shadowing variables | Confusing scope | Use renaming or different names |
Destructuring in Practice
// API response
const response = {
status: 200,
data: {
user: { id: 1, name: 'Alice' },
token: 'abc123'
}
};
const { status, data: { user: { id, name }, token } } = response;
// Array of objects (React map)
users.map(({ id, name, email }) => (
`<div>${id}: ${name} (${email})</div>`
));
// Config with defaults
function createServer({ port = 3000, host = 'localhost', debug = false } = {}) { }
// Swap without temp
let a = 1, b = 2;
[a, b] = [b, a];
// Return multiple values
function getMinMax(arr) {
return [Math.min(...arr), Math.max(...arr)];
}
const [min, max] = getMinMax([3, 1, 4, 1, 5]);
Pro Tip: Destructuring is essential in modern JavaScript — especially with React where you destructure props and state. Use object destructuring for readable parameter lists: function fn({ a, b, c }) instead of function fn(options). Use array destructuring for swaps and multiple return values. Use renaming ({ x: newX }) for clarity and defaults ({ x = 5 }) for optional values. The rest pattern (...rest) is perfect for omitting fields — like removing passwords before logging. Remember: defaults only apply to undefined, not null — and always provide = {} for optional parameter destructuring!
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!