We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Destructure

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 []

Assignment

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.