DEV Community

Cover image for What are the three dots (...) or spread operator in Javascript?
Johnny Simpson
Johnny Simpson

Posted on • Originally published at fjolt.com

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

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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

let numbers = [ 1999, 26, 3 ];

let thisDate = new Date(...number);
Enter fullscreen mode Exit fullscreen mode

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 ];
Enter fullscreen mode Exit fullscreen mode

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 ];
Enter fullscreen mode Exit fullscreen mode

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 };
Enter fullscreen mode Exit fullscreen mode

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 };
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (2)

Collapse
 
cisco profile image
Mahomed CISSOKHO

I was looking for this
thanks !

Collapse
 
smpnjn profile image
Johnny Simpson

no worries