|
1 | 1 | // Array Destructure |
2 | 2 |
|
3 | | -//? Q. What is array destructuring? |
| 3 | +// What |
4 | 4 | // - Array destructuring is a feature in JavaScript that allows you to extract values from an array and assign them to individual variables. |
5 | 5 |
|
6 | | -const array = [1, 2, 3, 4, 5]; |
| 6 | +const myArray = [1, 2, 3, 4, 5]; |
7 | 7 |
|
8 | | -//* Dry syntax |
9 | | -let variable1 = array[0]; |
10 | | -let variable2 = array[1]; |
11 | | -let variable3 = array[2]; |
| 8 | +// Dry syntax |
| 9 | +let variable1 = myArray[0]; |
| 10 | +let variable2 = myArray[1]; |
| 11 | +let variable3 = myArray[2]; |
12 | 12 | console.log(variable1); |
13 | 13 | console.log(variable2); |
14 | 14 | console.log(variable3); |
15 | 15 |
|
16 | | -//* Better syntax |
17 | | -let [variable4, variable5, variable6] = array; |
| 16 | +// Better syntax |
| 17 | +let [variable4, variable5, variable6] = myArray; |
18 | 18 | console.log(variable4); |
19 | 19 | console.log(variable5); |
20 | 20 | console.log(variable6); |
21 | 21 |
|
22 | | -//* Store element in single variable and creating new array using remaining elements. |
23 | | -let [variable7, ...newArray] = array; |
| 22 | +// Store element in single variable and creating new array using remaining elements. |
| 23 | +let [variable7, ...newArray] = myArray; |
24 | 24 | console.log(variable7); |
25 | 25 | console.log(newArray); |
26 | 26 |
|
27 | | -//* Skipping single element when storing array elements inside variables. |
28 | | -let [variable8, , variable9] = array; |
| 27 | +// Skipping single element when storing array elements inside variables. |
| 28 | +let [variable8, , variable9] = myArray; |
29 | 29 | console.log(variable8); |
30 | 30 | console.log(variable9); |
31 | 31 |
|
32 | | -//* Swapping values using array destructuring |
| 32 | +// Swapping values using array destructuring |
33 | 33 | let variable10 = "value1"; |
34 | 34 | let variable11 = "value2"; |
35 | 35 | [variable11, variable10] = [variable10, variable11]; |
|
0 commit comments