Spread syntax (three dots) in JavaScript

Spread syntax which is used by typing three dots (…) in JavaScript. It allows an array expression or string or anything which can be iterating to be expanded in places where zero or more arguments for function calls or elements for array are expected. It can also be used for an object expression to be expanded in places where zero or more key-value pairs for object are expected.

Spread syntax can be used for:

  • Array literals or string
  • Function Calls
  • Object literals (ECMAScript 2018)

How to use Spread syntax in Array literals?

Let consider below code in which we have two arrays.

Now here we want to merge values of “arr1” into the “arr2” after value “3” in “arr2”. To achieve this we used to follow below traditional way.

Here Spread of ECMAScript 2015 comes in the picture which simplifies the above code and allow us to achieve above output very easily. Consider below code:

Consider below experiment for easy array operations with Spread (three dots):

How to use Spread syntax in Function?

In function if you want to pass an array as an argument you have to use Function.Prototype.apply.

Let’s consider below code:

Using Spread above can be achieved with

Any argument in the function can be passed using spread

Using spread we can pass an array to a constructor where we can’t pass simple array to call constructor with new

How to use Spread syntax with object?

Before using Spread syntax with objects make sure your browser supports ECMAScript 2018 features.

If you are doing Shallow cloning or merging of the objects Spread syntax can be useful


As we have discussed Spread is used only with iterable, so if you will try below code it will throw an exception

Interested in JavaScript? Click here to read more JavaScript articles in Code4Developers

Yatendrasinh Joddha
I am a software engineer currently living in Gandhinagar, India. My interest is in web and software development. I am also interested in sharing my knowledge with people.

I have expertise in asp.net and related Microsoft technologies, with JavaScript frameworks and libraries like JQuery, KnockOut.js,and AngularJS.
Yatendrasinh Joddha on FacebookYatendrasinh Joddha on GithubYatendrasinh Joddha on LinkedinYatendrasinh Joddha on TwitterYatendrasinh Joddha on Wordpress

11 Replies to “Spread syntax (three dots) in JavaScript”

  1. var arr1 = [4,5]
    var arr2 = [1,2,3,…arr1,6,7]

    that’s too easy. You manually add it after the 3.
    But let’s imagine that you have
    var arr1 = [4,5]
    var arr2 = [1,2,3,6,7]

    and now want to have an arr3 that should look like [1,2,3,4,5,6,7] without just manually put in the … after the 3.

    1. you can just concatenate the two arrays and then sort the result…

      var arr1 = [4,5]
      var arr2 = [1,2,3,6,7]
      var arr3 = ([…arr1, …arr2]).sort()

Leave a Reply

%d bloggers like this: