Explain the concept of destructuring assignment for objects and arrays
TL;DR
Destructuring assignment is a syntax in JavaScript that allows you to unpack values from arrays or properties from objects into distinct variables. For arrays, you use square brackets, and for objects, you use curly braces. For example:
// Array destructuringconst [a, b] = [1, 2];// Object destructuringconst { name, age } = { name: 'John', age: 30 };
Destructuring assignment for objects and arrays
Destructuring assignment is a convenient way to extract values from arrays and objects into separate variables. This can make your code more readable and concise.
Array destructuring
Array destructuring allows you to unpack values from arrays into distinct variables using square brackets.
Basic example
const numbers = [1, 2, 3];const [first, second, third] = numbers;console.log(first); // 1console.log(second); // 2console.log(third); // 3
Skipping values
You can skip values in the array by leaving an empty space between commas.
const numbers = [1, 2, 3];const [first, , third] = numbers;console.log(first); // 1console.log(third); // 3
Default values
You can assign default values in case the array does not have enough elements.
const numbers = [1];const [first, second = 2] = numbers;console.log(first); // 1console.log(second); // 2
Object destructuring
Object destructuring allows you to unpack properties from objects into distinct variables using curly braces.
Basic example
const person = { name: 'John', age: 30 };const { name, age } = person;console.log(name); // Johnconsole.log(age); // 30
Renaming variables
You can rename the variables while destructuring.
const person = { name: 'John', age: 30 };const { name: personName, age: personAge } = person;console.log(personName); // Johnconsole.log(personAge); // 30
Default values
You can assign default values in case the property does not exist in the object.
const person = { name: 'John' };const { name, age = 25 } = person;console.log(name); // Johnconsole.log(age); // 25
Nested objects
You can destructure nested objects as well.
const person = { name: 'John', address: { city: 'New York', zip: '10001' } };const {name,address: { city, zip },} = person;console.log(name); // Johnconsole.log(city); // New Yorkconsole.log(zip); // 10001