Search⌘ K
AI Features

Spread Operator

Explore the use of the spread operator in JavaScript for arrays and objects, understand how it helps create copies and merge data without mutation, and see why it is essential in React for managing state and props efficiently.

Another great simplification has been the introduction of the spread operator (...) for objects and arrays. The use of this operator is not yet supported for objects in ES2015 because the specifics are still under discussion. However, this will change with ES2018 when it is added to the ECMAScript specification. Initially, it was added to arrays in ES2015. Using Babel, though, we can harness the power of the spread operator in our work with objects today. Many React projects make heavy use of the spread operator.

What is a spread operator?

The spread operator allows us to unpack values. Before ES2015, we had to extract arguments from an array to pass them to a function usingFunction.prototype.apply(). Let’s look at an example.

Node.js
function sumAll(number1, number2, number3) {
return number1 + number2 + number3;
}
var myArray = [1, 2, 3];
console.log(sumAll.apply(null, myArray));

Using the spread operator, which consists of three dots (), we can unpack these arguments, or spread them.

Node.js
function sumAll(number1, number2, number3) {
return number1 + number2 + number3;
}
var myArray = [1, 2, 3];
console.log(sumAll(...myArray));

As you can see, apply() is now unnecessary.


Spread operator with arrays

Spreading arguments is not just useful for function arguments. It can also be used to easily combine two arrays into one. Let’s visualize this with the help of an example.

Node.js
const greenFruits = ['kiwi', 'apple', 'pear'];
const redFruits = ['strawberry', 'cherry', 'raspberry'];
const allFruits = [...greenFruits, ...redFruits];
console.log(allFruits);

A new array is created that contains all values from greenFruits and all values from redFruits. But there’s more: a new array is also created for us, not just a reference to the old arrays. Due to the read-only mentality in React, the creation of new array proves useful when working with props. The spread operator can also be used to create a simple copy of an array:

const users = ['Manuel', 'Chris', 'Ben'];
const selectedUsers = [...users];

In the above example, selectedUsers is a copy of users and all of its values. If we change the users array, no complications for selectedUsers occur.

Spread operator with objects

Let’s shift our focus to how the spread operator works with objects. Using the spread operator with objects is very similar to using it with arrays. However, instead of using every single value, the operator uses every property that is enumerable in the object (such as properties used during a for(… in …) loop).

Note: Contrary to enumerable properties, non-enumerable properties are read-only. Hence, we cannot modify the values of such properties. The Object.defineProperty() method is used to create properties that are non-enumerable:

var person = {
    name: 'Ahmed'
};
person.age = '23';
person['country'] = 'Pakistan';
Object.defineProperty(person, 'salary',{
    value : '20000',
    enumerable: false
})

name, age, and country are enumerable properties in the above code snippet, whereas salary is non-enumerable.

The spread operator is a great choice to create objects:

Node.js
const globalSettings = { language: 'en-US', timezone: 'Berlin/Germany' };
const userSettings = { mutedUsers: ['Manuel'] };
const allSettings = {...globalSettings, ...userSettings};
console.log(allSettings);

The properties of each object can be found in the allSettings object. However, the spread operator is not limited to two objects. We can combine any number of objects into a new object. Even the combination of single properties is possible:

const userSettings = { mutedUsers: ['Manuel'] };
const settings = {
    ...userSettings,
    showWarnings: true,
}

If there are object properties with the same name in any two objects, the property in the object declared last will be used:

Node.js
const globalSettings = { language: 'en-US', timezone: 'Berlin/Germany' };
const userSettings = { language: 'de-DE' };
const allSettings = {...globalSettings, ...userSettings};
console.log(allSettings);

The userSettings object, which is declared after the globalSettings object, overrides the language property by providing a key that is identical to that in the globalSettings object.

The spread operator works similarly to the Object.assign() method in ES2015, which is also used occasionally in ES2015+ applications.

Note: Object.assign() mutates an existing object, whereas the spread operator creates a new object. In terms of writing React components and their props, we want to avoid creating mutations.

Let’s complete a quick exercise to conclude this lesson. Imagine you have two arrays of animals. The first is an array of aquatic animals called aquaticAnimals:

aquaticAnimals = ["otter", "shark", "bluefin tuna"]

The second array is an array of animals typically found in the rainforest, called rainforestAnimals:

rainforestAnimals = ["orang-utan", "elephant", "snake"]

Now, use the spread operator to combine all animals from each array into a single array called awesomeAnimals.

Node.js
aquaticAnimals = ["otter", "shark", "bluefin tuna"]
rainforestAnimals = ["orang-utan", "elephant", "snake"]
let awesomeAnimals;
// Write your code here