Spread and Rest Operators in Javascript

Spread and Rest Operators in Javascript

Introduction

Spread and Rest are lesser-known but very useful operators to work with arrays in modern Javascript.

The most useful cases of the spread operator include

  • Adding elements of an array into another
  • Copying arrays
  • Concatenation
  • Passing arguments into a function through an array

While the rest operator is a bit opposite to the spread operator

  • It converts the arguments of the function into an array to use within the functional scope.

With this little head-start, let's get started.

Syntax

The syntax for the Spread and Rest operators is quite simple, it's just 3 dots [...] followed by the array name.

...arrayName

Spread Operator Usage

1. Adding Elements of an Array into Another

Let's say we have an array containing three numbers: 3, 4, and 5

const initArray = [3, 4, 5]

and now we want an array containing five numbers: 1, 2, 3, 4, and 5

const finalArray = [1, 2, 3, 4, 5]

We can obviously hardcore the content in it, but we can also do this :

const initArray = [3, 4, 5]

const finalArray = [1, 2, ...initArray]

both outputs are the same. Here what the spread operator does is, it spreads the elements of initArray into the finalArray to act as elements of the finalArray. I have taken numbers here just for illustration, you can work with any data type or with different types of data.

2. Copying Arrays

We need to copy an array into another for multiple instances in day-to-day programming. The most logical way to do this would be :

const myArray = [1, 2, 3]
const copiedArray = myArray

Well, using this has a lot of disadvantages. Of which the major one is when you try pushing some data in 'copiedArray' it will also get pushed into 'myArray'. Like :

const myArray = [1, 2, 3]
const copiedArray = myArray

copiedArray.push(4)
console.log(copiedArray)
console.log(myArray)

will output

[1, 2, 3, 4]
[1, 2, 3, 4]

So the preferred solution is using the array function : .slice()

const myArray = [1, 2, 3]
const copiedArray = myArray.slice()

copiedArray.push(4)
console.log(copiedArray)
console.log(myArray)

which will output

[1, 2, 3, 4]
[1, 2, 3]

Now with the spread operator, what you can do is simply :

const myArray = [1, 2, 3]
const copiedArray = [...myArray]

this works great too!

What if here we don't use the spread operator? like :

const myArray = [1, 2, 3]
const copiedArray = [myArray] 

console.log(copiedArray)

it will output

[ [1, 2, 3] ]

as if myArray is the first element of copiedArray.

3. Concatenation

Concatenation through spread operator gives a lot of flexibility. We can

  • Concat as many arrays we want
  • Whichever order we want
  • Add custom element's within two arrays
const array1 = ['red', 'blue', 'green']
const array2 = ['yellow', 'purple']
const array3 = ['orange']

const array = [...array1, ...array3]
                      OR
const array = [...array3, ...array1, ...array2]
                      OR
const array = [...array1, 'grey', ...array2, ...array3]

4. Passing arguments in a function through an array

Normally we pass arguments to a function like :

function add(value_one, value_two) {
    console.log(value_one + value_two)
}

add(1, 2)

with spread operator, we can do is :

const args = [1, 2]

function add(value_one, value_two) {
    console.log(value_one + value_two)
}

add(...args)

At times, we pass more than the accepted number of arguments into a function :

const args = [1, 2, 3]

function add(value_one, value_two) {
    console.log(value_one + value_two)
}

add(...args)

but this will output the same: 3

So to handle multiple arguments, we use the rest operator.

Rest Operator Usage

Like I said above, with a Rest operator we can handle multiple arguments of a function. Basically what the Rest operator does is, convert all the arguments into an array to deal with. Like :

function sumOfAll(...args) {
    let sum = 0
    args.forEach(arg => {
        sum += arg
    })
    return sum
}

console.log(sumOfAll(1, 2, 3, 4, 5))

which will output ' 15 '

Rest Operator comes in handy when we don't know the number of arguments or the arguments is more than easy to handle.

If this article helped you a little make sure to comment and follow me : (_pratikpakhale)[twitter.com/_pratikpakhale]

Also, edits are appreciated!