Javascript

What are the three dots (...) or spread operator in Javascript?

Sponsor

The spread operator, spread syntax or 3 dots (...), is a type of syntax in Javascript which is used by both function calls and in arrays/objects. It has a multitude of different uses, so let's take a look at how we use the spread syntax in real Javascript code.

In function calls

We can use the 3 dots in Javascript function calls to convert an array into a set of arguments for a function. Let's look at an example. Below, our array is converted into the values for x, y, z and a.

let numbers = [ 1, 2, 3, 4 ]; let myFunction = function(x, y, z, a) { return x + y + z + a; } // Returns 10 myFunction(...numbers);

This can be combined with other values, so the following is also valid, using the same function as before:

let numbers = [ 1, 2 ]; // Returns 15 (i.e. 5 + 7 + 1 + 2) myFunction(5, 7, ...numbers);

This can also be used when calling a constructor with new, for example:

let numbers = [ 1999, 26, 3 ]; let thisDate = new Date(...number);

Merging Arrays

Another useful way to use the spread syntax is to merge arrays. For example, we can merge two separate arrays into a new one using two spread syntaxes:

let x = [ 1, 2, 3 ]; let y = [ 4, 5, 6 ]; // Returns [ 1, 2, 3, 4, 5, 6 ] let newArray = [ ...x, ...y ];

Similar to before, we can combine this with other values and still get the same outcome:

let x = [ 1, 2 ]; // Returns [] 4, 5, 1, 2 ] let newArray = [ 4, 5, ...x ];

Merge Objects

Finally, we can use the spread syntax to merge objects. In the below example, we merge two objects with key/value pairs into one object:

let obj1 = { name: "John" }; let obj2 = { age: 114 }; // Returns { name: "John", age: 114 } let newObj = { ...obj1, ...obj2 };

If we try to merge two objects and there is a duplicate key, the second object will take precedence and overwrite the first one, as shown below:

let obj1 = { name: "John" }; let obj2 = { name: "Jake" }; // Returns { name: "Jake" } let newObj = { ...obj1, ...obj2 };

And that's how spread syntax work - they let us run functions with arrays easily, and are good for merging objects and arrays. You can find more Javascript tutorials at the bottom of this page.

Last Updated Tuesday, 9 November 2021
Johnny Simpson
Johnny Simpson

More Tips and Tricks Javascript

Subscribe for Weekly Dev Tips

Subscribe to our weekly newsletter, to stay up to date with our latest web development and software engineering posts via email. You can opt out at any time.

Not a valid email