Mark As Completed Discussion

Destructuring

In JavaScript, destructuring assignment allows us to extract individual values from arrays or objects and assign them to variables. This can make working with complex data structures more convenient and can lead to cleaner and more readable code.

Array Destructuring

Array destructuring allows us to extract values from an array and assign them to variables in a single line of code. The syntax for array destructuring is as follows:

JAVASCRIPT
1const numbers = [1, 2, 3];
2
3const [a, b, c] = numbers;

In the example above, we have an array numbers with three elements. We then use array destructuring to extract the values and assign them to variables a, b, and c. Now we can use these variables elsewhere in our code.

Object Destructuring

Object destructuring allows us to extract values from an object and assign them to variables. The syntax for object destructuring is as follows:

JAVASCRIPT
1const person = {
2  name: 'John',
3  age: 30,
4  city: 'New York'
5};
6
7const { name, age, city } = person;

In the example above, we have an object person with three properties. We then use object destructuring to extract the values and assign them to variables name, age, and city.

Destructuring can also be combined with default values and rest elements to handle more complex scenarios. It provides a powerful and flexible way to work with data in JavaScript.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment