Register to get access to free programming courses with interactive exercises

Rest syntax and destructuring JS: Arrays

The power of destructuring is most apparent where it is used in conjunction with the rest syntax. The rest parameter allows you to collapse some elements during destructuring. For example, you can use it to unpack an array into its first element and all the others:

const fruits = ['apple', 'orange', 'banana', 'pineapple'];

// ... – rest
const [first, ...rest] = fruits; 
console.log(first); // 'apple'
console.log(rest); // ['orange', 'banana', 'pineapple']

The ...rest notation means that you should take all elements that are left after destructuring and place them in an array named rest. You can give this array any name you want. The rest parameter is triggered at the very end when all other data has already been unpacked into their constants (or variables). That's why it's called the rest syntax.

Similarly, any array is unpacked into any number of elements + all the rest. The rest syntax has limitations. It cannot appear anywhere except at the end of the array.

const [head, ...tail] = fruits; 
// tail = ['orange', 'banana', 'pineapple']

const [first, second, ...rest] = fruits; 
// rest = ['banana', 'pineapple']

const [first, second, third, ...rest] = fruits; 
// rest = ['pineapple']

// If there are no elements, then rest will contain an empty array
const [first, second, third, oneMore, ...rest] = fruits; 
// rest = []

In situations where we're only interested in part of an array, but the first elements are not necessary, then it's better to use the slice() array method:

// slice returns a new array, but doesn't change the old one
const rest = fruits.slice(1);
console.log(rest); // ['orange', 'banana', 'pineapple'];

The rest can also be used when destructuring strings.

const [first, second, ...rest] = 'some string';
console.log(first); // => 's'
console.log(second); // => 'o'
console.log(rest); // => [ 'm', 'e', ' ', 's', 't', 'r', 'i', 'n', 'g' ]

Note that after unpacking the rest of the string into rest we end up with an array, not a string.

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

Bookmate
Health Samurai
Dualboot
ABBYY