JavaScript ES6+ Features – Destructuring Assignment Explained
What is destructuring in JavaScript
Introduction
Destructuring assignment, introduced in ES6 (ECMAScript 2015), is a syntax enhancement in JavaScript that allows you to unpack values from arrays or properties from objects into distinct variables. This powerful feature makes your code cleaner, shorter, and more readable.
Array destructuring lets you extract values from an array and assign them to variables in a single, elegant statement.
const [a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2
const [first, , third] = [10, 20, 30];
console.log(third); // 30
const [x = 5, y = 10] = [undefined];
console.log(x); // 5
console.log(y); // 10
Object destructuring extracts values based on property names.
const user = { name: 'Alice', age: 25 };
const { name, age } = user;
console.log(name); // Alice
const { name: username } = user;
console.log(username); // Alice
const { role = 'User' } = user;
console.log(role); // User
const person = { info: { firstName: 'Bob', lastName: 'Smith' } };
const { info: { firstName } } = person;
console.log(firstName); // Bob
const colors = ['red', ['green', 'blue']];
const [primary, [secondary]] = colors;
console.log(secondary); // green
function greet({ name, age }) {
console.log(`Hello ${name}, age ${age}`);
}
greet({ name: 'Sam', age: 30 });
function sum([a, b]) {
return a + b;
}
console.log(sum([4, 6])); // 10
Parsing API responses
const { data, error } = await fetchData();
Simplifying React props
function Profile({ name, email }) {
return <p>{name} - {email}</p>;
}
Working with configs
const config = { host: 'localhost', port: 3000 };
const { host, port } = config;
Destructuring properties that don’t exist will result in undefined
.Destructuring is shallow, not deep.Does not create a deep copy.
JavaScript destructuring makes your code shorter, cleaner, and easier to manage. Whether you're unpacking API responses or simplifying parameters in a function, this ES6+ feature is a powerful addition to your JavaScript toolkit.