Skip to main content

Posts

Showing posts with the label Spread operator

How to Spread in Javascript - ES 6

Spread syntax was introduced as part of Javascript in the ES2015/ECMAS-6.

This allows iterable likes array, object or string to get expanded.

Spread can be used in following ways:
in array : [...iterableArray, 3 , 'four', 5]
in object : {...iterableObj}

The spread operator is very useful for concat, copying,apply, expanding, math operations,etc in array and objects. Let discuss each in detail.

Concat
var arr1 = [1,2,3];
var arr2 = [4,5,6];

without spread
var concatenatedArray = arr1.concat(arr2); // [1,2,3,4,5,6]

with spread
var concatenatedArray = [...arr1, ...arr2 ] // [1,2,3,4,5,6]

Copying
var arr1 = [1,2,3];
var arr2 = [...arr1];
arr2.push(4);
console.log(arr2); // [1,2,3,4]
console.log(arr1); // [1,2,3]

Replacement for apply
var add = (a,b,c) => a+b+c;
var arr1 = [1,2,3];
add(...arr1); // replacing add.apply(null,arr1);

Expanding array
var programming = ["Java", "NodeJs", "Python"];
var subjects = ["Physics", ...programmi…