Hey there! I am shafeek makandar, student at iNeuron. I love learning new stuffs and while doing so I also wanted to share my knowledge through this blogs.
Today we will learn about Spread and Rest operators in javascript ๐
- spread : used to unpack the elements from array or object.
- rest : used to pack the elements from array or object.
note : both the operators denoted with ... dots, but their use cases are different.
Spread
Let's understand where we use spread operator ๐
- To make copy or clone of an array or object.
const array = [ 1, 2, 3, 4, 5 ];
const newArray = [ ...array ];
console.log(newArray); // output : [ 1, 2, 3, 4, 5 ]
const user = {
id : '1',
name : 'john',
city : 'newyork'
}
const newUser = {
...user,
}
console.log(newUser); // output: { id: '1', name: 'john', city: 'newyork' }
note: both user & newUser are two different objects having same element.
- point to be note that spread will only make shallow copy not deep clone, let's understand with example.
const products = {
id : '1',
name : [ 'mobile', 'tablet'];
}
const newProducts = {
...products,
}
products.name.push('laptop');
console.log(newProducts); //output : { id: '1', name: [ 'mobile', 'tablet', 'laptop' ] }
noticed in the above code, when we push "laptop" into the products objects name property, newProducts properties also updated.
Note : when there is nested elements present in object or array, spread operator only copy the reference of the property.
- merge array or objects.
We can merge arrays or objects using spread operator
const array_1 = [ 1, 2, 3 ];
const array_2 = [ 4, 5, 6 ];
const newArray = [ ...array_1, ...array_2 ];
console.log(newArray); //output: [ 1, 2, 3, 4, 5, 6 ]
const user = {
name : 'hitesh',
profession : 'CTO at iNeuron',
}
const adress = {
city : 'bangalore'
}
const newUsers = {
...user,
...adress,
}
console.log(newUsers); //output : { name: 'hitesh', profession: 'CTO at iNeuron', city: 'bangalore' }
- converting string into array
const name = "iNeuron";
const array = [ ...name ];
console.log(array); //output: [ 'i', 'N', 'e', 'u', 'r', 'o', 'n' ];
Rest
- mainly we use rest operator in the functions parameters or arguments.
for example we have array, given that to calculate sum.
function add(num1, num2, num3){
return num1 + num2 + num3;
}
console.log(add(5, 3, 6)); // output : 14
- but by using rest operator also we can achive this
let sum = 0;
function add(...array){
console.log(array); // output : [ 5, 3, 6 ]
for(let element of array){
sum = sum + element;
}
return sum;
}
console.log(add(5, 3, 6)); // output : 14
Note : what rest operator does is, it packs the parameters into array. when we log the array we will get [ 5, 3, 6 ].