Destructuring assignment is a powerful feature in JavaScript that allows you to extract values from arrays or properties from objects and assign them to variables in a concise and expressive way.
Destructuring assignment can be useful for:
Array destructuring in JavaScript is a syntax that allows you to extract individual elements from an array and assign them to distinct variables. Enclose the variables you want to assign values to within square brackets []
on the left-hand side of the assignment operator =
, and place the array you want to destructure on the right-hand side.
const nums = [1, 2, 3, 4, 5];
// Elements are assigned to variables based on their position in the array
const [x, y, z] = nums;
console.log(x); // 1
// Collect any remaining elements into a new array
const [first, ...rest] = nums;
console.log(rest); // [2, 3, 4, 5]
// Default values in case elements are missing
const [foo = 5] = [];
console.log(foo); // 5
// Swapping variable values without a temporary variable
let a = 10, b = 20;
[a, b] = [b, a];
console.log(a); // 20
console.log(b); // 10
Object destructuring in JavaScript is a syntax that allows you to extract individual properties from an object and assign them to distinct variables in a single line of code, significantly reducing the boilerplate code needed compared to traditional methods like dot notation or bracket notation.
const person = {
name: "John",
age: 30,
address: { street: "Champs-Élysées", city: "Paris" },
};
// Properties are assigned to variables based on their names within the object
const { name, age } = person;
console.log(name); // John
console.log(age); // 30
// Extract properties from nested objects
const {
address: { city },
} = person;
console.log(city); // Paris
// Specify default values in case properties are missing
const { job = "Engineer" } = person;
console.log(job); // Engineer
// Assign a property to a variable with a different name
const { name: fullName } = person;
console.log(fullName); // John
// Extract properties directly from function arguments
function greet({ name, greeting = "Hello" }) {
console.log(`${greeting}, ${name}!`);
}
greet({ name: "byby" }); // Hello, byby!