JavaScript Spread Syntax

What is the three dots ( … ) in JavaScript

Marcio Junior
2 min readAug 12, 2022

A quick tutorial about spread syntax, just in case you still are not familiar with it.

Photo by Stephanie LeBlanc on Unsplash

Spread syntax allows you to expand an iterable, such as an array or string. Let’s take a string as an example:

let myString = "abc";
console.log({...myString});

This code produces the output: {0: “a”, 1: “b”, 2: “c”}

Note that the operator was inside curly braces, which is one of the two places you are allowed to use the operator. The second place is as arguments of a function call:

let myArray = ["a", "b", "c"];function myFunction(param1, param2, param3) {
console.log(param1 + ", " + param2 + ", " + param3);
}
myFunction(...myArray);

Produces the result: a, b, c

Ok, now that we covered the basics, let´s try to understand something more useful. Spread syntax can also work with object literals, like this one:

let myObject1 = {
a: "my a value",
b: "my b value"
}
console.log({...myObject1});

The result of spreading this object is: {a: “my a value”, b: “my b value”}

You can take advantage of this syntax to concatenate or merge objects. Personally, I found this useful when I have an object with default values and want to modify one or more values at once:

const myObject1 = {
a: "my a value",
b: "my b value"
}
const myObject2 = {
...myObject1,
b: "new b value"
}
console.log({...myObject2});

That’s all for today. Keep practicing and feel free to contact me if you have doubts.

Reference: Spread syntax (…) — JavaScript | MDN (mozilla.org)

--

--