Friday, 1 February, 2019 UTC


Summary

Spread Operator or Spread Syntax was introduced as part of the ES2015 release and have some really useful features. Basically it expands an iterable such as Array expression, Object expression or a String.
Spread Operator looks like this ... then the iterable expression for example items that would look like ...items.
Here’s an example of what it looks like.
const fruits = ['Apple', 'Mango', 'Banana'];

console.log(...fruits); // Apple Mango Banana

// is equivalent to
console.log(fruits[0], fruits[1], fruits[2]); // Apple Mango Banana
So from the word itself, it spreads an iterable expression. Another example to solidify your understanding.
const nums = [1, 2, 3];

console.log(...nums); // 1 2 3
console.log([...nums]); // [ 1, 2, 3 ]
console.log(nums); // [ 1, 2, 3 ]
From our second example you can see that we put the spread operator inside the open and close brackets to have the same result as the original array.
Now that we have the basic knowledge about it. Let’s proceed on its use cases.
 
 
Copying or Cloning
You can copy an expression and that copy is a clone so whatever you do with it, it doesn’t affect the original expression.
const arr = ['Code', 'dam'];
const arr2 = [...arr];

console.log(arr); // [ 'Code', 'dam' ]
console.log(arr2); // [ 'Code', 'dam' ]

arr2[2] = "is Awsome!";

// arr2 is changed but it doesnt affect the original which is arr
console.log(arr); // [ 'Code', 'dam' ]
console.log(arr2); // [ 'Code', 'dam', 'is Awsome!' ]


// not using spread operator but pass as reference
const arr3 = arr;

arr3[0] = "Sad";

console.log(arr3); // [ 'Sad', 'dam' ]
console.log(arr); // [ 'Sad', 'dam' ]
The old way of copying arrays are using Array.from or slice array method.
const arr = ['Code', 'dam'];
const arr2 = Array.from(arr);
const arr3 = arr.slice();

console.log(arr); // [ 'Code', 'dam' ]
console.log(arr2); // [ 'Code', 'dam' ]
console.log(arr3); // [ 'Code', 'dam' ]
 
 
Apply to a new expression
We could adopt the contents of the existing iterable expression to a new expression.
const oldArray = [1, 2, 3];
const newArray = [...oldArray, 4, 5, 6];

console.log(newArray); // [ 1, 2, 3, 4, 5, 6 ]


const oldObj = {
    name: 'Codedam'
};
const newObj = {
    ...oldObj,
    location: 'Philippines'
}

console.log(newObj); // { name: 'Codedam', location: 'Philippines' }
 
 
Concatenate Multiple Expressions
We could also concatenate multiple iterable expression in any position you want to a new expression.
// Array

const arr1 = [1, 2];
const arr2 = [4, 5];

const newArray = [2, ...arr1, 3, ...arr2, 9];

console.log(newArray); // [ 2, 1, 2, 3, 4, 5, 9 ]


// Object

const obj1 = {
    name: 'Codedam'
};
const obj2 = {
    age: 22
};
const newObj = {
    ...obj1,
    ...obj2,
    location: 'Philippines'
}

console.log(newObj); // { name: 'Codedam', age: 22, location: 'Philippines' }
The other way to do it is using Object.assign with objects and concat for arrays.
// Array

const arr1 = [1, 2];
const arr2 = [4, 5];

const newArray = arr1.concat(arr2);

console.log(newArray); // [ 1, 2, 4, 5 ]


//Object

const obj1 = {
    name: 'Codedam'
};
const obj2 = {
    age: 22
};
const newObj = Object.assign({location: 'Philippines'}, obj1, obj2)

console.log(newObj); // { location: 'Philippines', name: 'Codedam', age: 22 }
 
 
Spread as arguments
Before we use Function.prototype.apply to set array items into arguments but now we could do it with spread syntax.
function sum(x, y, z) {
    return x + y + z;
}

const arr = [1, 2, 3];


console.log(sum.apply(null, arr));  // 6
Example using spread.
function sum(x, y, z) {
    return x + y + z;
}

const arr = [1, 2, 3];


console.log(sum(...arr)); // 6
 
 
Rest Syntax
Rest Parameter looks exactly the same with Spread Syntax however rest combines the arguments into a single array. Using it means where expecting zero or more arguments to be pass in our function.
function muliplyByTen(...nums) {
    return nums.map( num => num * 10 );
}

console.log(muliplyByTen(1, 2, 3)); // [ 10, 20, 30 ]


// Combo using Spread Operator and Rest Operator

const arr = [5, 4, 3]
console.log(muliplyByTen(...arr)); // [ 50, 40, 30 ]
Also we could expect/name our first to n parameter and then assign the Rest Parameter on the end.
function muliply(miltiplier, ...nums) {
    return nums.map( num => num * miltiplier );
}

console.log(muliply(2, 2, 3, 9)); // [ 4, 6, 18 ]
Note than you could only put the Rest Syntax on the last formal parameter or else you would have an Syntax Error.
 
 
Application on in-built JavaScript functions
You can also use spread syntax on in-built JavaScript functions.
const arr = [10, 4, 5, 2, 9];

console.log(Math.max(...arr)); // 10
console.log(Math.min(...arr)); // 2


const dateFields = [2019, 1, 2];
const date = new Date(...dateFields);

console.log(date); // 2019-02-01T16:00:00.000Z
 
 
Split String
Spread Syntax can also spread strings and turn then to an array of characters which also happens when you use split function.
const str = 'Codedam';

console.log([...str]); // [ 'C', 'o', 'd', 'e', 'd', 'a', 'm' ]
console.log(str.split(''));  // [ 'C', 'o', 'd', 'e', 'd', 'a', 'm' ]
 
 
Benefits of using Spread Operator
    • Avoids mutation or the cloned expression doesn’t affects the original.
    • Better way to concat arrays (Put anywhere you like)
    • Better than using apply method (Array.prototype.push.apply(arr1, arr2) vs [...arr1, ...arr2])
    • Shorter code (some might think its not a benefit but once you get use to it, it is)
 
 
You could also checkout the MDN website to check more about the spread syntax.
To learn more checkout our latest JavaScript articles. Also feel free to comment any suggestion, correction and improvements that you might want to share. that’s all, Cheers!
The post Spread Operator – Just so you know JavaScript appeared first on Codedam.