Destructuring
function
ES6
Extracts values from arrays or properties from objects into distinct variables.
Syntax
const { a, b } = obj; const [x, y] = arr;
Example
javascript
// Object destructuring
const user = { name: 'Alice', age: 28, city: 'London' };
const { name, age, city = 'Unknown' } = user;
console.log(name, age); // Alice 28
// Rename
const { name: userName } = user;
console.log(userName); // Alice
// Array destructuring
const [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(first); // 1
console.log(rest); // [3, 4, 5]
// Swap variables
let a = 1, b = 2;
[a, b] = [b, a];