Home > Article > Web Front-end > Powerful Examples of Destructuring Assignments in JavaScript
Destructuring assignment is a syntactic sugar introduced in ES6 that allows you to unpack values from arrays or objects into variables. It can significantly simplify your code and make it more readable.
Basic Example:
const numbers = [1, 2, 3, 4]; const [first, second, ...rest] = numbers; console.log(first); // Output: 1 console.log(second); // Output: 2 console.log(rest); // Output: [3, 4]
const [first, , third] = numbers; console.log(first, third); // Output: 1 3
const nestedArray = [[1, 2], [3, 4]]; const [[a, b], [c, d]] = nestedArray; console.log(a, b, c, d); // Output: 1 2 3 4
Basic Example:
const person = { name: 'Alice', age: 30, city: 'New York' }; const { name, age, city } = person; console.log(name, age, city); // Output: Alice 30 New York
const { name: firstName, age, city } = person; console.log(firstName, age, city); // Output: Alice 30 New York
const { name, age = 25, city } = person; console.log(name, age, city); // Output: Alice 30 New York
const person = { name: 'Alice', address: { street: '123 Main St', city: 'New York' } }; const { name, address: { street, city } } = person; console.log(name, street, city); // Output: Alice 123 Main St New York
Destructuring can be used to swap variables concisely:
let a = 10; let b = 20; [a, b] = [b, a]; console.log(a, b); // Output: 20 10
You can destructure function parameters to make them more readable:
function greet({ name, age }) { console.log(`Hello, ${name}! You are ${age} years old.`); } greet({ name: 'Alice', age: 30 });
By effectively using destructuring assignment, you can write cleaner, more concise, and more readable JavaScript code.
The above is the detailed content of Powerful Examples of Destructuring Assignments in JavaScript. For more information, please follow other related articles on the PHP Chinese website!