JS Spread Operator
Written By: Avinash Malhotra
Updated on
Spread Operator (...)
JavaScript Spread Operator ... is used to allows iterables (string, array) to expand where zero or more arguments or elements (array) are required. Spread Operator turns elements of an array into arguments of function. spread operator is also used in Objects to copy another object data into new object being constructed.
In Arrays, spread expands array into elements.
Spread syntax can be used in
- Function Arguments
- Arrays
- Objects
Spread Operator Example
3
function add(x,y){return x+y}
const nums=[1,2];
console.log( add(...nums) );
Spread in function arguments
Spread in function arguments can be used to spread arrays data into arguments. It converts an array elements into arguments of function called.
Sum Array elements using spread
6
function add(x,y,z){ return x+y+z};
let data=[1,2,3];
console.log(add(...data));
Check maximum value i array
3
const data=[1,2,3];
console.log(Math.max(...data));
Check minimum value i array
1
const data=[1,2,3];
console.log(Math.min(...data));
earlier apply method was used to achieve same results.
Math.max.apply(null,[1,2,3]); returns 3
Math.min.apply(null,[1,2,3]); returns 1
Spread Operator in Arrays
Spread Operator is also used in an array. It can be used in push method, concat method etc. Here are some examples of spread operator in arrays.
push array into array
['a', 'b', 'c', 'd']
let a1=['a','b'];
let a2=['c','d'];
a1.push(...a2);
console.log(a1);
concat arrays
['a', 'b', 'c', 'd']
let a1=['a','b'];
let a2=['c','d'];
let a3=a1.concat(...a2);
console.log(a3);
split string arrays
['a', 'b', 'c', 'd']
let str="abcd";
let arr=[...str];
console.log(arr);
Spread Operator in Objects
Spread Operator can also be used in objects. For example, to bind an object properties and values into another object.
Spread in object
{name: 'john', id:111, city: 'delhi', pin: 110001}
const address={city:"delhi", pin:110001};
const user={name:"john",id:111, ...address};
console.log(user);