React JS ES6: destructuring
ReactJS destructuring
1 Overview
📘 Destructuring arrays
Array destructuring
is a way to extract values from an array and assign them to separate variables.
It allows you to unpack the values of an array into separate variables.
2 Why do we need it
Array destructuring can be a useful tool for extracting values from arrays and assigning them to separate variables. It can make your code more concise and easier to read, especially when working with large or complex arrays.
Here is the old way of assigning array items to a variable:
App.js
Here is the new way of assigning array items to a variable With destructuring:
3 How to use destructuring
Here’s an example of array destructuring:
App.js
You can also use destructuring to skip elements or assign default values:
App.js
In the first example, the second element of the arr array is skipped, and in the second example, default values are assigned to the b2 and c2 variables if the corresponding elements of the arr2 array are not present.
Array destructuring can be a convenient way to extract values from arrays and assign them to separate variables. It can make your code more concise and easier to read.
You can also use destructuring to skip elements or assign default values:
4 More examples
4.1 Nested arrays
You can use destructuring to extract values from nested arrays:
4.2 Rest syntax
The rest syntax allows you to capture the remaining elements of an array in a separate variable:
4.3 Swapping variables
You can use destructuring to easily swap the values of two variables:
4.4 Function arguments
You can use destructuring to specify function arguments:
4.5 Object destructuring
You can also use destructuring with objects. Here’s an example: