@Sharad823
Destructuring is confusing at first.
Let’s take a look at the first example code
const [a, b] = [1, 2, 3, 4, 5, 6];
console.log(a, b); // 1, 2
is the same as
const arr = [1, 2, 3, 4, 5, 6];
const a = arr[0]; // 1
const b = arr[1]; // 2
So instead of writing variable arr
and then declare variable a
and b
, you could just simplifiy it by typing const [a, b] = [1, 2, 3, 4, 5, 6];
So destructuring is about less typing. That’s it.
The second example is almost the same
Instead of writing it like this
const arr = [1, 2, 3, 4, 5, 6];
const a = arr[0]; // 1
const b = arr[1]; // 2
const c = arr[4]; // 5
you could write it like this
const [a, b,,, c] = [1, 2, 3, 4, 5, 6];
console.log(a, b, c); // 1, 2, 5
Now about array. You could write a new array with an array literal
[]
but it won’t do anything since you don’t save it within a variable right?
if you want to save it in a variable you write something like
const arr = []
now variable arr
has the value of []
. In JS you could write any value inside an array, really, any value: boolean, number, string
etc. Let’s populate it with number
of 1
and 2
.
const arr = [1, 2];
You could also refer the value to a variable like this:
let a = 1;
let b = 2;
const arr = [a, b];
But what if you want to swap the value of a
and b
?
you could hardcode it
let a = 1;
let b = 2;
a = b;
b = a;
Correct? No, you can’t do it. Try it in your browser console.
a
and b
now have the same value which is 2
. So how do we swap value in JS?
We declare new variable to store it.
let a = 1;
let b = 2;
let temp = a;
a = b;
b = temp;
Yes, it is quite verbose to just swap value in JS. So can you make it simple? With destructuring, you can. How? I hope you already know by this point how to make it less verbose.
let a = 1;
let b = 2;
// since we can't do this
// a = b;
// b = a;
// we can do
const arr = [a, b];
a = arr[1] // 2
b = arr[0] // 1
// or you could use array literal and destructuring it
[a, b] = [b, a]
Remember =
is about assigning a value on the right to the left.
Sorry for my boring and long explanation. Feel free to ask anything if you still confuse with this challenge.