Spread and Rest Operators in JavaScript

It’s hard to get away from the spread operator – the three dots or ellipses – in modern JavaScript code bases. And that’s because it’s such a nifty tool packing a lot of functionality in its unassuming form. Depending on the context, it also doubles as the rest operator. Well, what is it and what can you do with it? Let’s take a look.

Cloning Objects

If you haven’t checked out my post on cloning objects in JavaScript, you can review that here. In that post, we learned that we can use the spread operator to make a copy of an existing object. Here’s an example:

let oldEmployee = {
  firstName: 'Jack',
  lastName: 'Jones'

// Use spread operator for cloning
let newEmployee = {...oldEmployee};
newEmployee.firstName = 'Jeff';
newEmployee.lastName = 'Smith';

console.log(newEmployee.firstName) // Jeff
console.log(oldEmployee.firstName) // Jack

Combining Two Arrays

Another use case for the spread operator is combining arrays into one. Here’s an example:

let fullTimers = ['Jack', 'Jill'];
let partTimers = ['Mary', 'John'];
let employees = [...fullTimers,...partTimers];

// Output:
// ["Jack", "Jill", "Mary", "John"]

Spread a String

The spread operator works with arrays, objects but also works with strings. Ever had the need to individually inspect each character in a string? Well, you can do it quite concisely using the spread operator. Take a look at this example, below:

let test = 'Hello World!';

// Output:
"H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d", "!"

Rest Operator

Well, this operator with the three dots is also known as the rest operator. If you want to write a method where you have to take a variable number of parameters as input, you can use the rest operator. Let’s look at an example:

function getEmployeeAttributes (firstName, lastName, employeeId, ...hobbies){
  console.log(firstName, lastName, employeeId, hobbies);

getEmployeeAttributes('Tom', 'Testing', 'EMP123', 'stamp collection', 'oil painting', 'playing the cello')

// Output:
"Tom", "Testing", "EMP123", ["stamp collection", "oil painting", "playing the cello"]

Note that when using the rest operator as a method parameter, it must appear as the last parameter. In the example above, we can take a variable number of hobbies for each employee as we can’t predetermine the number of hobbies each person will have. In this context, we call the three dots “a rest operator” as it collects the rest of the parameters that are passed in after firstName, lastName and employeeId into an array.

Closing Remarks

The ... operator doubles both the spread and rest operator. The name depends on the context in which you are using it. While there were other ways to solve the use-cases in my above-mentioned examples prior to the advent of this operator, this new(er) keyword lets you do them in a terse manner.

Leave a Comment

Your email address will not be published. Required fields are marked *