35. What is destructuring assignment in JavaScript?
In JavaScript, destructuring assignments allow you to assign multiple values from an array or object to multiple variables in a single line. This can make your code easier to read and write, especially when dealing with complex data structures.
Here are two examples of destructuring assignments:
1. Assigning values from an array:
const [a, b, c] = [1, 2, 3];
console.log(a); // Output: 1
console.log(b); // Output: 2
console.log(c); // Output: 3
In this example, we are assigning the values of the array `[1, 2, 3]` to the variables `a`, `b`, and `c`. We use square brackets to specify that we're working with an array, and we list out the names of the variables we want to create.
2. Assigning values from an object:
const { name, age } = { name: 'John', age: 30 };
console.log(name); // Output: John
console.log(age); // Output: 30
In this example, we are assigning the values of the object `{ name: 'John', age: 30 }` to the variables `name` and `age`. We use curly braces to specify that we're working with an object, and we list out the names of the properties we want to access.
Destructuring assignments can also be used to assign values from multiple arrays or objects in a single line. Here's an example:
const [a, b, ...c] = [1, 2, 3, 4, 5];
console.log(a); // Output: 1
console.log(b); // Output: 2
console.log(c); // Output: [3, 4, 5]
In this example, we are assigning the values of the array `[1, 2, 3, 4, 5]` to the variables `a`, `b`, and `c`. We use square brackets to specify that we're working with an array, and we list out the names of the first two variables (`a` and `b`) followed by three dots (`...`) to indicate that we want to assign the remaining values to an array variable called `c`.