Destructuring
Extract values from objects and arrays
#destructuring #syntax #es6
Destructuring
Extract values from objects and arrays with concise syntax.
Object Destructuring
const user = {
name: 'Alice',
age: 30,
email: 'alice@example.com'
};
// Basic destructuring
const {name, age} = user;
console.log(name); // Alice
// Rename variables
const {name: userName, age: userAge} = user;
console.log(userName); // Alice
// Default values
const {role = 'user'} = user;
console.log(role); // user
// Nested destructuring
const config = {
server: {
host: 'localhost',
port: 3000
}
};
const {server: {host, port}} = config;
console.log(host); // localhost
Array Destructuring
const colors = ['red', 'green', 'blue', 'yellow'];
// Basic destructuring
const [first, second] = colors;
console.log(first); // red
// Skip elements
const [, , third] = colors;
console.log(third); // blue
// Rest operator
const [primary, ...others] = colors;
console.log(others); // ['green', 'blue', 'yellow']
// Swap variables
let a = 1, b = 2;
[a, b] = [b, a];
console.log(a, b); // 2 1
Function Parameters
function printUser({name, age}) {
console.log(`${name} is ${age} years old`);
}
printUser({name: 'Bob', age: 25}); // Bob is 25 years old
Discover another handy tool from EditPDF.pro