DEV Community

Cover image for Rest vs spread in javascript
Omor Faruk
Omor Faruk

Posted on

Rest vs spread in javascript

In javascript has lot of miss conception like spread and rest they look same or identical but there behaviour something different. Today in this articel we will discover what is the main dfferent between rest and spread.

Spread & Rest syntex...array

let array1 = [1,2]
let array2 = [3,4]
// we want to concat two array
// we can concat two way like

let array3 = [...array1, ...array2]
// another way 
let array3 = array1.concat(array2)

Enter fullscreen mode Exit fullscreen mode

First example is concat through
spread operator you can use spread like you have 10 array you can concat via spread.

Second example is built-in javascript.

You can use it on string array.

let strArray = [..."developer life is tough"]
// output like devide all letter and space like array just try your self
Enter fullscreen mode Exit fullscreen mode

The most important thing of array you can copy an array it called shallow copy.

Just keep in mind that this one only clone the first level. This work with primitive type, like number and string but not object

let arrToClone = [1,2,3,4,5,6,7,8]
let shallowCopy = [...arrToClone]
Enter fullscreen mode Exit fullscreen mode

Let understand use of spread in object.

let obj1 ={
  age: 23,
  profession : 'developer'
}

let obj2 ={
  language: 'javascrip',
  girlfriend : false
}

let obj3 = {...obj1, ... obj2}
console.log(obj3)
// It will marge two object 

// we can shallow copy with object but conditions is obly first lavel like array 

let shallowCopyObj = {...obj1}
Enter fullscreen mode Exit fullscreen mode

Last thing is Function.

In javascript function we can use it two way.

Rest

//this it rest
function exp(x,y,...other){
  return other;
}
// rest operator
exp(1,2,3,4,5,6,7,8,9)
// return [3,4,5,6,7,8,9]
Enter fullscreen mode Exit fullscreen mode

Spread

function exp2(a,b,c){
  return a+b+c
}
let number = [1,2,3]

// spread operator
exp2(...number) 

Enter fullscreen mode Exit fullscreen mode

Finally, we cover main different beetween rest and spread operations.

Summary

  • when you use (...) on function parameter is called Rest

  • when you use (...) on function argument is called Spread

  • Spread operator help to merge object and array but conditionally.😄

Top comments (0)