What is spread syntax in ES6 and how to use it?

Continuing our explanation for ES6 new features, we will review the spread operator. What is the magic spread syntax in ES6? The spread syntax is simply three dots: 

It allows an iterable to expand in places where 0 or more arguments likeIndefinite number of arguments (function calls) or  elements (array literals) or key-value pairs (object literals) are expected.

Let us have a look at some of its usages to get a better idea:

Calling functions without Apply

To call a function with array argument we needed to use apply and use this syntax:

function doSomething (x, y, z) { }

var args = [0, 1, 2];

// Call the function, passing args

doSomething.apply(null, args);

This old problem has been solved using the spread operator. So we can now omit apply and use the spread syntax to call the function like this:

<span class="token punctuation">doSomething</span><span class="token punctuation">(...</span>args<span class="token punctuation">)</span><span class="token punctuation">;</span>

It is that simple and fun!

Copying arrays

To copy an array we pass a reference to the second one so they will have same values:

© 2020
Azadeh Faramarzi

This site is created and maintined by Azadeh Faramarzi , A passionate developer, sport and code lover who loves to share and write when she has some time.