

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 5
click for more info
Not enough gems
Cost: 6 gems
1: Arrays
incomplete
2: Array Length
incomplete
3: Array Spread
incomplete
4: Includes
incomplete
5: For...of Loops
incomplete
6: Slicing Arrays
incomplete
7: const Arrays
incomplete
8: Destructure
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
You can destructure an array just like you can an object.
const nums = [1, 2, 3];
function double([a, b, c]) {
return [a * 2, b * 2, c * 2];
}
const [x, y, z] = double(nums);
console.log(x, y, z);
// 2 4 6
If you're only interested in the first element, you can destructure just that element, from the same code:
const [x] = double(nums);
console.log(x);
// 2
If you're unsure how many elements there are, you can use the rest operator ... to capture the rest of the elements into a new array:
const [x, ...theRestOfThem] = double(nums);
console.log(x);
// 2
console.log(theRestOfThem);
// [4, 6]
If you over-destructure, you'll get undefined:
const [x, y, z, a] = double(nums);
console.log(x, y, z, typeof a);
// 2 4 6 undefined
The variable created with ... is always an array; if there are no remaining elements, it will simply be an empty array []
const [x, y, z, ...a] = double(nums);
console.log(x, y, z, a);
// 2 4 6 []
Textio maintains a list of messages to send to users. Complete the getPrimaryAndBackupMessages function by using array destructuring.
The function takes an array of messages as input, and returns an object with two properties:
primary: the first message in the array.backups: an array containing all the remaining messages (if any).If the array is empty, return an object with primary set to undefined and backups set to an empty array.