ES6 Destructuring
The older method of accessing and assigning values from an array was indexing:
const myArray = ['car', 'jet', 'spaceship'];
const landVehicle = myArray[0];
const airVehicle = myArray[1];
const spaceVehicle = myArray[2];
However, ES6 has introduced a new method called destructuring, which enables us to access and assign values from an array easily:
const [ landVehicle, airVehicle, spaceVehicle ] = myArray;
console.log (landVehicle);
The above method is much neater and requires less code.
We can also skip the elements we don't want to capture, for example, we can skip airVehicle but add an extra comma:
const [ landVehicle, , spaceVehicle ] = myArray;
Note
The
constkeyword is for defining constant terms, you can also use theletkeyword in the Destructuring statement.
Tak for dine kommentarer!
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat
Can you explain how destructuring works with objects?
What happens if the array has more or fewer elements than variables in the destructuring assignment?
Can you show more examples of skipping elements or using default values with destructuring?
Fantastisk!
Completion rate forbedret til 2.7
ES6 Destructuring
Stryg for at vise menuen
The older method of accessing and assigning values from an array was indexing:
const myArray = ['car', 'jet', 'spaceship'];
const landVehicle = myArray[0];
const airVehicle = myArray[1];
const spaceVehicle = myArray[2];
However, ES6 has introduced a new method called destructuring, which enables us to access and assign values from an array easily:
const [ landVehicle, airVehicle, spaceVehicle ] = myArray;
console.log (landVehicle);
The above method is much neater and requires less code.
We can also skip the elements we don't want to capture, for example, we can skip airVehicle but add an extra comma:
const [ landVehicle, , spaceVehicle ] = myArray;
Note
The
constkeyword is for defining constant terms, you can also use theletkeyword in the Destructuring statement.
Tak for dine kommentarer!