Array destructuring allows you to unpack values from arrays into separate variables.
Basic Example
const array = [1, 2, 3];
const [a, b, c] = array; console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
Skipping Values
const array = [1, 2, 3, 4];
const [a, , b] = array; console.log(a); // 1
console.log(b); // 3
Using Rest Operator
const array = [1, 2, 3, 4, 5];
const [a, b, ...rest] = array; console.log(a); // 1
console.log(b); // 2
console.log(rest); // [3, 4, 5]
Object destructuring allows you to extract properties from objects into variables.
Basic Example
const obj = { x: 1, y: 2, z: 3 };
const { x, y, z } = obj; console.log(x); // 1
console.log(y); // 2
console.log(z); // 3
Renaming Variables
const obj = { x: 1, y: 2 };
const { x: a, y: b } = obj; console.log(a); // 1
console.log(b); // 2
Default Values
const obj = { x: 1 };
const { x, y = 2 } = obj; console.log(x); // 1
console.log(y); // 2
Nested Destructuring
const obj = { name: 'John', address: { city: 'New York', state: 'NY' }
};
const { name, address: { city, state } } = obj; console.log(name); // John
console.log(city); // New York
console.log(state); // NY
Function Parameters
Destructuring can also be used to simplify the handling of function parameters, especially when dealing with options objects.
function greet({ name, age }) { console.log(`Hello, my name is ${name} and I am ${age} years old.`);
} const person = { name: 'Alice', age: 25 };
greet(person); // Hello, my name is Alice and I am 25 years old.
These are some of the common ways to use destructuring in JavaScript. It can make your code cleaner and more readable by reducing the amount of boilerplate code required to extract values from arrays and objects.
Discover more from Coursity
Subscribe to get the latest posts sent to your email.