Destructuring is a powerful feature in JavaScript that allows you to extract values from arrays or objects into variables in a concise and readable way. It’s like unpacking a suitcase full of goodies! 🧳
Destructuring Arrays 📦
Let’s start with arrays. Suppose you have an array of fruits:
const fruits = ["apple", "banana", "orange"];
To extract the first two fruits into separate variables, you can use array destructuring:
We created two variables, firstFruit and secondFruit.
The [firstFruit, secondFruit] syntax tells JavaScript to extract the first two elements from the fruits array and assign them to the corresponding variables.
Skipping Elements ⏩
You can skip elements in an array by using commas: