- In JavaScript, destructuring is a powerful feature that allows us to quickly unpack values from arrays or objects into variables. This can make your code cleaner, more readable, and easier to maintain.
->in this post you will learn to destruct arrays, Skipping a value in the array, and Switching variables
Destructuring Arrays
We use destructuring to retrieve elements from the array and store them into variables.
Array Destructuring assignment = []
Example:
const arr = ['rice', 'pizza', 'chicken'];
// without Destructuring:
const foodOne = arr[0];
const foodTwo = arr[1];
const foodThree = arr[2];
console.log(foodOne, foodTwo, foodThree); // rice pizza chicken
// with Destructuring
const [food1, food2, food3] = arr;
console.log(food1, food2, food3); // rice pizza chicken
- as we can see in this example, destructuring made our work much easier and saves a lot of time, we use const or let to create the destructuring, then inside square brackets [] we can write the variable names for the values we want in the array, but be careful that in destructuring arrays the order of values in the array is important, the order in the destructuring assignment will be the order in the array, so you have to be aware of this.
Note: Destructuring Doesn't destroy the original array, we just UNPACK it, for illustration:
console.log(arr); // rice pizza chicken
- so, we still have our values inside the original array.
Skipping a value:
- if we did not want to unpack a certain value from an array, to skip that one leave an empty space (a 'hole') in your destructuring pattern, so that it does not destruct that value, for example:
- if for some reason we did not want the pizza, then write it like this:
let [food1, , food3] = arr;
console.log(food1, food3); // rice chicken
Switching variables:
if we wanted the first food to be chicken instead of rice, and the third one rice instead of chicken, we can switch their places and their values will be switched, example:
[food1, food3] = [food3, food1];
console.log(food1, food3); // chicken rice
I hope this helped you get a better understanding of JavaScript array destructuring. Feel free to ask any questions in the comments below :)
Top comments (0)