Destructuring assignment in JavaScript
What is Destructuring?
Destructuring assignment is a JavaScript syntax that allows you to unpack values from arrays or extract properties from objects into distinct variables. Introduced in ES6.
Array Destructuring
javascript
const [a, b, c] = [1, 2, 3];
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3Skipping Elements
javascript
const [first, , third] = [1, 2, 3];
console.log(first); // 1
console.log(third); // 3Default Values
javascript
const [a = 10, b = 20] = [1];
console.log(a); // 1
console.log(b); // 20 (default)Rest Pattern
javascript
const [head, ...tail] = [1, 2, 3, 4];
console.log(head); // 1
console.log(tail); // [2, 3, 4]Swapping Variables
javascript
let a = 1, b = 2;
[a, b] = [b, a];
console.log(a); // 2
console.log(b); // 1Object Destructuring
javascript
const { name, age } = { name: "Alice", age: 25 };
console.log(name); // "Alice"
console.log(age); // 25Renaming Variables
javascript
const { name: userName, age: userAge } = { name: "Alice", age: 25 };
console.log(userName); // "Alice"
console.log(userAge); // 25Default Values
javascript
const { name, role = "user" } = { name: "Alice" };
console.log(role); // "user" (default)Nested Destructuring
javascript
const user = {
name: "Alice",
address: {
city: "Kyiv",
zip: "01001"
}
};
const { address: { city, zip } } = user;
console.log(city); // "Kyiv"
console.log(zip); // "01001"Rest in Objects
javascript
const { id, ...rest } = { id: 1, name: "Alice", age: 25 };
console.log(id); // 1
console.log(rest); // { name: "Alice", age: 25 }Function Parameters
javascript
// Object destructuring in parameters
function greet({ name, age }) {
return `Hello, ${name}! You are ${age}.`;
}
greet({ name: "Alice", age: 25 });
// With defaults
function createUser({ name, role = "user", active = true } = {}) {
return { name, role, active };
}Common Use Cases
Importing Named Exports
javascript
import { useState, useEffect } from 'react';API Response
javascript
const { data, error, loading } = await fetchUser(id);Multiple Return Values
javascript
function getMinMax(arr) {
return { min: Math.min(...arr), max: Math.max(...arr) };
}
const { min, max } = getMinMax([3, 1, 4, 1, 5]);Important:
Destructuring makes code more readable and concise. Use it for function parameters, API responses, imports, and anywhere you need to extract specific values from objects or arrays.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.