Hey fellow creators
Destructuring is a nice way to create some variables from an array or an object! Let's learn how to do it in less than a minute.
If you prefer to watch the video version, it's right here :
You have to follow the same syntax every time. For example:
const array = ["#ff0000", "#008000", "#0000ff"]; const [red, green, blue] = array; console.log(red, green, blue);
If you look in your console, you'll see that each name is linked to its colour:
You can give some default values, just in case that array is empty:
const array = ; const [red = "1", green = "2", blue = "3"] = array; console.log(red, green, blue);
In your console will therefore show "1 2 3".
Remove one colour name from the array but leave the comma:
const array = ["#ff0000", "#008000", "#0000ff"]; const [red = "1", , blue = "3"] = array; console.log(red, blue);
It'll ignore the second value and simply create a constant for red and blue:
const fruits = ["kiwi", "strawberry", "lemon"]; const [first, ...others] = fruits; console.log(first, others);
It created one constant for the first element and an array of the remaining element named "others" :
Come and take a look at my Youtube channel: https://www.youtube.com/c/TheWebSchool