JavaScript Destructuring & Spread
Master destructuring assignment, spread operators, and rest parameters for cleaner, more expressive JavaScript code
40 min•By Priygop Team•Last updated: Feb 2026
Destructuring Assignment
Destructuring allows you to extract values from objects and arrays into distinct variables using a syntax that mirrors the construction of array and object literals. This feature makes code more readable and concise.
Destructuring Features
- Array Destructuring: Extract values from arrays
- Object Destructuring: Extract properties from objects
- Nested Destructuring: Extract from nested structures
- Default Values: Provide fallback values
- Rest Parameters: Collect remaining elements
- Spread Operator: Expand arrays and objects
Destructuring Examples
Example
// Array destructuring
const numbers = [1, 2, 3, 4, 5];
const [first, second, third] = numbers;
console.log(first, second, third); // 1 2 3
// Skip elements
const [a, , c, , e] = numbers;
console.log(a, c, e); // 1 3 5
// Rest operator
const [head, ...tail] = numbers;
console.log(head); // 1
console.log(tail); // [2, 3, 4, 5]
// Default values
const [x = 0, y = 0, z = 0] = [1, 2];
console.log(x, y, z); // 1 2 0
// Object destructuring
const person = {
name: 'John',
age: 30,
city: 'New York',
country: 'USA'
};
const { name, age, city } = person;
console.log(name, age, city); // John 30 New York
// Rename variables
const { name: fullName, age: userAge } = person;
console.log(fullName, userAge); // John 30
// Default values in objects
const { name: userName, age: userAge2, hobby = 'reading' } = person;
console.log(userName, userAge2, hobby); // John 30 reading
// Nested destructuring
const user = {
id: 1,
profile: {
firstName: 'Jane',
lastName: 'Doe',
contact: {
email: 'jane@example.com',
phone: '123-456-7890'
}
}
};
const { profile: { firstName, contact: { email } } } = user;
console.log(firstName, email); // Jane jane@example.com
// Function parameters
function greet({ name, age = 18 }) {
return `Hello ${name}, you are ${age} years old!`;
}
console.log(greet({ name: 'Alice' })); // "Hello Alice, you are 18 years old!"
// Return value destructuring
function getUser() {
return {
id: 1,
name: 'Bob',
email: 'bob@example.com'
};
}
const { id, name: userName3 } = getUser();
console.log(id, userName3); // 1 Bob
// Spread operator
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4, 5, 6]
// Copy arrays
const original = [1, 2, 3];
const copy = [...original];
copy[0] = 10;
console.log(original); // [1, 2, 3]
console.log(copy); // [10, 2, 3]
// Spread with objects
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const merged = { ...obj1, ...obj2 };
console.log(merged); // { a: 1, b: 2, c: 3, d: 4 }
// Override properties
const baseConfig = { theme: 'dark', language: 'en' };
const userConfig = { theme: 'light' };
const finalConfig = { ...baseConfig, ...userConfig };
console.log(finalConfig); // { theme: 'light', language: 'en' }
// Rest in objects
const { name: userName4, ...otherProps } = person;
console.log(otherProps); // { age: 30, city: 'New York', country: 'USA' }Practice Exercise: Destructuring
Example
// Exercise: Build a Data Processor
class DataProcessor {
constructor() {
this.data = [];
}
addData(...items) {
this.data.push(...items);
return this;
}
processUsers(users) {
return users.map(({ name, age, email, ...rest }) => ({
displayName: `${name} (${age})`,
contact: email,
metadata: rest
}));
}
extractCoordinates(locations) {
return locations.map(({ lat, lng, name, ...details }) => ({
position: [lat, lng],
locationName: name,
additionalInfo: details
}));
}
mergeConfigs(...configs) {
return configs.reduce((merged, config) => ({
...merged,
...config
}), {});
}
splitArray(array) {
const [first, second, ...rest] = array;
return {
first,
second,
rest,
total: array.length
};
}
extractQueryParams(url) {
const [, queryString] = url.split('?');
if (!queryString) return {};
return queryString.split('&').reduce((params, pair) => {
const [key, value] = pair.split('=');
return { ...params, [key]: decodeURIComponent(value || '') };
}, {});
}
}
// Test the data processor
const processor = new DataProcessor();
// Test user processing
const users = [
{ name: 'John', age: 30, email: 'john@example.com', role: 'admin' },
{ name: 'Jane', age: 25, email: 'jane@example.com', role: 'user' }
];
const processedUsers = processor.processUsers(users);
console.log('Processed users:', processedUsers);
// Test location processing
const locations = [
{ lat: 40.7128, lng: -74.0060, name: 'New York', country: 'USA' },
{ lat: 51.5074, lng: -0.1278, name: 'London', country: 'UK' }
];
const coordinates = processor.extractCoordinates(locations);
console.log('Coordinates:', coordinates);
// Test config merging
const config1 = { theme: 'dark', language: 'en' };
const config2 = { theme: 'light', debug: true };
const config3 = { apiUrl: 'https://api.example.com' };
const mergedConfig = processor.mergeConfigs(config1, config2, config3);
console.log('Merged config:', mergedConfig);
// Test array splitting
const numbers = [1, 2, 3, 4, 5, 6, 7, 8];
const split = processor.splitArray(numbers);
console.log('Split result:', split);
// Test query params extraction
const url = 'https://example.com/search?q=javascript&page=1&sort=name';
const params = processor.extractQueryParams(url);
console.log('Query params:', params);