Destructuring Explained
Key Concepts
- Array Destructuring
- Object Destructuring
- Default Values
- Nested Destructuring
- Rest Parameters
- Swapping Variables
Array Destructuring
Array destructuring allows you to extract values from arrays and assign them to variables in a concise way. This is done by matching the positions of elements in the array with the variables in the destructuring pattern.
Example:
let [a, b, c] = [1, 2, 3]; console.log(a); // Outputs: 1 console.log(b); // Outputs: 2 console.log(c); // Outputs: 3
Object Destructuring
Object destructuring allows you to extract properties from objects and assign them to variables with the same name. This is done by matching the property names in the object with the variable names in the destructuring pattern.
Example:
let {name, age} = {name: "John", age: 30}; console.log(name); // Outputs: John console.log(age); // Outputs: 30
Default Values
Default values can be assigned to variables during destructuring to ensure they have a fallback value if the extracted value is undefined.
Example:
let {x = 10, y = 20} = {x: 5}; console.log(x); // Outputs: 5 console.log(y); // Outputs: 20
Nested Destructuring
Nested destructuring allows you to extract values from nested objects or arrays. This is done by creating a nested pattern that matches the structure of the data.
Example:
let {address: {city, zip}} = {name: "John", address: {city: "New York", zip: "10001"}}; console.log(city); // Outputs: New York console.log(zip); // Outputs: 10001
Rest Parameters
Rest parameters allow you to collect the remaining elements of an array or object into a new array or object during destructuring. This is done using the rest syntax (...).
Example:
let [first, ...rest] = [1, 2, 3, 4]; console.log(first); // Outputs: 1 console.log(rest); // Outputs: [2, 3, 4]
Swapping Variables
Destructuring can be used to swap the values of two variables without needing a temporary variable. This is done by creating a destructuring pattern that swaps the values directly.
Example:
let x = 10, y = 20; [x, y] = [y, x]; console.log(x); // Outputs: 20 console.log(y); // Outputs: 10