Spread and Rest with Code Snippets

Spread and Rest with Code Snippets

Spread Operator:

Spread Operator came into existence after es6 was introduced to javascript. The spread Operator is represented using (...) it is mostly used in array not only array it is also used in iterable objects.

The spread operator allows you to spread out the elements from an iterable.

Spread unpack the elements of iterable elements into a list.

let arrayOne = [10,20,30,40]
let arrayTwo = [50,60,70,80]

const newArray = arrayOne.concat(arrayTwo)
console.log(newArray)

//output
[
  10, 20, 30, 40,
  50, 60, 70, 80 
]

so in the above example, I am creating a new array with the help of concat but I can do the same thing with the help of the spread operator as well let's see with an example:

const anotherArray = [...arrayOne, ...arrayTwo]
console.log(anotherArray)

[
  10, 20, 30, 40,
  50, 60, 70, 80 
]

Note: Spread allows you to spread the element from an iterable what does it actually mean let me show you an example.

let username = "deepak"
let newusername = [...username]

console.log(newusername)

//Output
[ 'd', 'e', 'e', 'p', 'a', 'k' ]

in the output, it is pretty clear that the elements are spread so now the statement is making some sense

statement: The spread operator allows you to spread out the elements from an iterable.

Spread Operator With Objects:

We can also add some new key-value pairs:

# Adding a new key-value pair 

let PersonInfo = {
  username: 'deepak kumar',
  email : 'deepak@gmail.com',
  employeeId : 2345,
  profession: 'Fullstack Developer'
 }

let displayResult = {...PersonInfo, Location: 'Odisha'}
console.log(displayResult)

Output
-------
{
  username: 'deepak kumar',
  email: 'deepak@gmail.com',        
  employeeId: 2345,
  profession: 'Fullstack Developer',
  Location: 'Odisha'
}

Copying the elements from one array to another using Spread:

let playersName = ['Rohit', 'Virat','Dhoni','Hardik']
let newArray = [...playersName]


newArray.push('Surya')
console.log(newArray)
console.log(playersName)

Output
-------
[ 'Rohit', 'Virat', 'Dhoni', 'Hardik', 'Surya' ]
[ 'Rohit', 'Virat', 'Dhoni', 'Hardik' ]

Note: here I am pushing one more value to the newArray but look at the output after pushing, the value is only getting added to newArray that means the original array is not getting affected.

so performing this operation with the help of spread will not do any changes to the Original Array but if I do it without spread then the changes will affect the original array into an example for more clarity.

// Performing the same operation without using the spread operator


let playersName = ['Rohit', 'Virat','Dhoni','Hardik']
let newArray = playersName


newArray.push('Surya')

console.log(newArray)
console.log(playersName)

Output
------
[ 'Rohit', 'Virat', 'Dhoni', 'Hardik', 'Surya' ]
[ 'Rohit', 'Virat', 'Dhoni', 'Hardik', 'Surya' ]

Rest Parameter :

The rest parameter was also introduced after es6. It same as Spread Operator because both are represented by using ... but both work differently using rest operator we can have an indefinite number of arguments as an array

it can store n number of arguments as an array

syntax

function functionName(a,b,c, ...d){

}

[ ...d ] is called the rest parameter

const playerNames = (playerOne, playerTwo, ...names) =>{
  console.log(`${playerOne} ${playerTwo} 
  ${names}
    `)

}
playerNames('Dhoni', 'Virat', 'Rohit', 'Klrahul')

In the above Example:

  1. playerOne is being mapped to Dhoni

  2. playerTwo is being mapped to Virat

  3. And the rest of the parameters Rohit and Kl Rahul were being mapped to

How not to use the rest parameter:

The rest parameter should be at the last because it is used to collect all the remaining arguments into an array otherwise we will get error

function functionname(a,b, ...c, d){//
    function Body
}
This is the wrong syntax we should not be writing like this
function functionname(a,b,c, ...d){
    functionBody
}

This is the right one, the rest parameter should be on the last

using rest in arrow functions:

const playerNames = (...names) =>{
  for(let i in names){
    console.log(`${names[i]}`)
  }

}
playerNames('Dhoni' ,'Virat' ,'Rohit' ,'Klrahul')

output
-------
Dhoni
Virat
Rohit
Klrahul

Using rest in function declaration:

function displayNumbers(a,b,c,...d){
    console.log(a)
    console.log(b)
    console.log(c)
    console.log(d)
}
displayNumbers(10,20,30,40,50,60,70,80,90)

Output
-------
10
20
30
[ 40, 50, 60, 70, 80, 90 ]

Using rest in function expression:


let result = function(a,b,c,...d){
  console.log(a)
  console.log(b)
  console.log(c)
  console.log(d)
}
result(10,20,30,40,50,60,70,80,90)

Output
------
10
20
30
[ 40, 50, 60, 70, 80, 90 ]

Program Example The find the sum using rest in arrow Functions:

let findSum = (...numbers) =>{
  let total = 0
  for(let i in numbers){
    total = total+numbers[i]
  }
  return total
}

console.log(findSum(10,20,30,40,50))

Output
------
150

In the above example, the (...numbers) will be behaving as a rest operator.