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 :
1. The syntax.
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:
2. You can also give some default values.
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".
3. You can also ignore some values!
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:
4. Create a constant for all the remaining parts of an array.
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" :
You now know how destructuring works in Javascript!
Come and take a look at my Youtube channel: https://www.youtube.com/c/TheWebSchool
Happy coding!
Enzo.
Top comments (0)