Close

JavaScript - Expanding iterable elements with Spread Syntax

[Updated: Jul 24, 2018, Created: Jul 24, 2018]

ES6 (ECMAScript 2015) introduced spread syntax which can be used to expand an iterable (array or string) into individual function parameters or literal elements. Let's understand that with examples.

Expanding iterable into function parameters

In following example we want array elements to be expanded into function's individual arguments while calling the function (we are not using spread syntax yet):

function test(a, b, c) {
    console.log(a);
    console.log(b);
    console.log(c);
}
var arr = [1, 2, 3];
test(arr);

Now let's use spread syntax, we simply need three dots (...) before array in the function call:

function test(a, b, c) {
    console.log(a);
    console.log(b);
    console.log(c);
}
var arr = [1, 2, 3];
test(...arr);

Different numbers of arguments:

function test(a, b, c) {
    console.log(a);
    console.log(b);
    console.log(c);
}
var arr = [1, 2, 3, 4, 5];
test(...arr);

Using additional arguments:

function test(a, b, c, d) {
    console.log(a);
    console.log(b);
    console.log(c);
    console.log(d);
}
var arr = [1, 2, 3];
test(...arr, 10);
console.log("---");
test(10, ...arr);

spread operator is an alternative to pre-existing Function.prototype.apply() method:

function test(a, b, c) {
    console.log(a);
    console.log(b);
    console.log(c);
}
var arr = [1, 2, 3, 4, 5];
test.apply(null, arr);

Following example applies Spread syntax on String.substring(start, end) method:

var s = "Taste the javascript";
var arr = [10, 20];
var s2 = s.substring(...arr);
console.log(s2);

Expanding iterable into array literal

var arr = [1, 2, 3, 4, 5];
var arr2 = [100, ...arr, 200];
console.log(arr2);
var arr = [1, 2, 3, 4, 5];
var arr2 = [100, 200];
var arr3 = [...arr, ...arr2];
console.log(arr3);

Expanding string

function test(a, b, c) {
    console.log(a);
    console.log(b);
    console.log(c);
}
var s = "pal";
test(...s);
var s = "pal";
var arr = [1, 3, ...s, 5];
console.log(arr);

See Also