ES6 Spread Explained

Arslan ur Rehman Iqbal
Level Up Coding
Published in
2 min readJun 29, 2019

--

ES6 has brought us many cool features, one of which is Spread syntax (). As per MDN documentation:

Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

At its core level, what Spread does is expand an iterable. That iterable can be an array or a string or an object. We will look into these iterables one by one and see how these work with Spread.

Arrays & Spread

Suppose we have a function that logs a full name as follows:

function PrintFullName (firstName, middleName, lastName){
console.log (firstName + “ “ + middleName + “ “ + lastName);
}
var Professor = [“Albus”, “Percival”, “Dumbledore”];
//Before ES6
PrintFullName (Professor[0], Professor[1], Professor[2]);
// using Spread
PrintFullName (…Professor);
// expected output: Albus Percival Dumbledore

The 3 dots in second approach is the Spread operator. The Spread operator iterated through the array and expanded that array and provided function arguments as separate values.

Consider another example here. Suppose we have two arrays and we want to add one array’s elements into another. It is much simpler to do this using Spread:

var arr1 = [1,2];
var arr2 = [3,4];
var combinedArr = […arr1, …arr2];
console.log (combinedArr); // expected output: [1,2,3,4]

Strings & Spread

A Javascript string is just a series of characters enclosed in a double quotation. Since its a series of characters, the Spread syntax will read a string value same as it read from an array and will seperate it in form of single characters.

var str = “Some String”;
var strArr = […str];
console.log (strArr); // expected output: [“S”, “o”, “m”, “e”, “ “, “S”, “t”, “r”, “i”, “n”, “g”]

Objects & Spread

A simple JS object is very much similar to a JSON object — a key and a value pairing.

var jsObject = {
Name : ‘John’,
};

We can use spread to combine an existing object and create more complex object:

var empData1 = {
Name: ‘Trevor’,
Gender: ‘M’,
Age: 31
};
var empData2 = {
State: ‘Pennsylvania’,
City: ‘Pittsburgh’
};
var empDataComplete = {…empData1, …empData2 };
console.log(empDataComplete); // expected output: {Name: “Trevor”, Gender: “M”, Age: 31, State: “Pennsylvania”, City: “Pittsburgh”}

So that’s how Spread operator works in Javascript. Hope that was helpful. Thanks for reading.

--

--