Skip to content

Commit 0231156

Browse files
committed
ft(readme): add a readme about destructuring in js
1 parent 77d8e02 commit 0231156

File tree

1 file changed

+43
-1
lines changed

1 file changed

+43
-1
lines changed

docs/JavaScript_Advance/destructuring.md

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,4 +32,46 @@ This is a bit repetative and now with ES6 destructuring assignment, completely u
3232
const { name, age, college } = a;
3333
```
3434

35-
This may look a bit weird, but let's walk through it together. You can see that the open bracket directly follows the `const`, followed by the three different properties that we are assigning to variables by the same name. In essence what we are doing is extracting the value of `name`, `age`, and `college` from the `a` object and assigning those values to `const` variables by the exact same name.
35+
This may look a bit weird, but let's walk through it together. You can see that the open bracket directly follows the `const`, followed by the three different properties that we are assigning to variables by the same name. In essence what we are doing is extracting the value of `name`, `age`, and `college` from the `a` object and assigning those values to `const` variables by the exact same name.
36+
37+
## Destructuring and Assignment
38+
There is a time when you want to destruct an item from an array and immediately name it, with javascript you can do it.
39+
40+
```js
41+
const { name: surname } = a;
42+
```
43+
If you console the name and surname both will display print `Swapnil`.
44+
45+
### Destructuring Array
46+
Sometime data is saved in an array datastructure, we can destruct them if we want
47+
```js
48+
const array = [1, 2, 3, 4]; // Array Declaration
49+
```
50+
How to access the items? we have options
51+
> option 1
52+
53+
When we want to skip specific item
54+
```js
55+
const [first, second, , fourth] = array; // Array Destructuring
56+
```
57+
Outoput is `1`, `2`, `4` // notice we skipped `third 3`
58+
> Option 2
59+
60+
When you want all items from array
61+
```js
62+
const [first, second, third, fourth] = array; // Array Destructuring
63+
```
64+
Outoput is `1`, `2`, `3`, `4` // all are printed
65+
66+
Always check your array length before, and then use the power of destructuring.
67+
68+
## Destructuring and Combination
69+
We can use our destructuring skills to get a specific item and combine the rest data. How to do it? Basically we need to use javascript `Spread operator`
70+
71+
```js
72+
const bigArray = [ 1,2,3,4,5,6,6,7,8,9];
73+
```
74+
```js
75+
const [firstItem, ...remainItems] = bigArray
76+
```
77+
The output will be first item will be `1` and remaining items will be combained in array `[2, 3, 4, 5, 6, 6, 7, 8, 9]`

0 commit comments

Comments
 (0)