Home

Rest and Spread operators in JavaScript

The rest and spread operators are introduced in ES2015/ES6. The easiest way to remember these two operators is(this is what I use)

Rest with strings

var [...a] = "Hello!"
// a → ["H", "e", "l", "l", "o", "!"]
var [a,b,...c]  = '12345'
// a → "1"
// b → "2"
// c → ["3", "4", "5"]

Rest in Arrays

var [a,b,...c]  = [1,2,3,4,5]
// a → 1
// b → 2
// c → [3, 4, 5]
// Copy without reference issues

var arr = [1,2,3]
var [...arr2] = arr

arr[0]=2
// arr → [2, 2, 3]
// arr2→ [1, 2, 3]

The copying of arrays using rest operators should be used cautiously, because when there are nested elements(such as objects) in the array the reference of the nested element still exists after it's copied.

Rest in Objects

var {a,b,...c}  = { a: 1, b: 2,c:3,d:4}
// a → 1
// b → 2
// c → {c: 3, d: 4}

The copying of objects can be done as we did for arrays in above examples, and it should be noted that nested elements will still have the reference when copied using this method.

Rest in Functions

For e.g., you want to accept any number of values passed to a function, you use rest operator.

function takeMultiArg(a,b,...c){
 console.log(a)
 console.log(b)
 console.log(c)
}

takeMultiArg('hello','world','this','is','utopia')
// Output:
// 'hello'
// 'world'
// ["this", "is", "utopia"]

The first two arguments in above examples work as normal parameters, but all the remaining arguments that are passed to the function will be captured by the variable c, because of the rest operator.

Even if you pass 3 arguments to the above function the third argument will be stored inside an array, because of rest operator.

takeMultiArg('hello','world','this')

// c → ["this"]

If the ... is on left side of '=' then it is rest operator, and if it is on the RHS(right hand side) then it is spread operator. Similarly if it is in function call then it is spread operator, and if it is in function parameters(in function definition) it is rest operator :)

Spread with arrays(Similar to rest operator)

// Copying Arrays
const arr = [1,2,3]
const arrCopy = [...arr]
// Merging two arrays
const arr = [1,2,3]
const newArr = [4,5]
const mergedArray = [...newArr, ...arr]

// mergedArray → [4, 5, 1, 2, 3]

Spread with objects

// Merging two objects
const obj = { a: 1, b: 2 }
const newObj = {c:3}
const objCopy = { ...obj, ...newObj }

// objCopy → { a: 1, b: 2, c: 3 }

While merging objects with spread operator, note that if same key exists in both of the objects that are being merged, then the latter will override the former.

// Merging two objects
const obj = { a: 1, b: 2 }
const newObj = {c:3, a:4}
const objCopy = { ...obj, ...newObj }

// objCopy → { a: 4, b: 2, c: 3 }

Spread in functions

function sum(a,b,c){
 return a+b+c;
}

const nums = [1,2,3];
sum(...nums) // returns 6


Last Updated on

Next Post: GraphProtocol: TS2322 null assignment in Subgraph →

Comments