The Rest Operator

The rest operator looks just like its twin, the spread operator, and while it not might be as frequently used, it is nonetheless very useful.

Destructuring

The rest operator can be used to get access to the rest of an object or array that you are destructuring.

const names = ['Westley', 'Farm Boy', 'Dread Pirate Roberts', 'The Man in Black']

// name: 'Westley'
// nickname: 'Farm Boy'
// aliases: ['Dread Pirate Roberts', 'The Man in Black']
const [name, nickname, ...aliases] = names
const countRugan = {
name: 'Rugan',
title: 'Count',
specialty: 'Torture',
fingers: 11,
toes: 10
}

// fingers: 11
// toes: 11
// otherAttributes: { name: 'Rugan', title: 'Count', specialty: 'Torture' }
const { fingers, toes, ...otherAttributes } = countRugan

Function Arguments

The rest operator when used with function arguments essentially makes the arguments object obsolete. As opposed to a strange, specialized, array-like object, rest arguments provide an actual array that you can use like any other array.

const addFriends = (person, ...friends) => ({
...person,
friends
})

const westley = { name: 'Westley', girlfriend: 'Buttercup' }

// { name: 'Westley', girlfriend: 'Buttercup', friends: ['Inigo', 'Fezzik'] }
addFriends(westley, 'Inigo', 'Fezzik')