The difference between Rest and spread operator in JavaScript

The difference between Rest and spread operator in JavaScript

In this post we will give you information about The difference between Rest and spread operator in JavaScript. Hear we will give you detail about The difference between Rest and spread operator in JavaScriptAnd how to use it also give you demo for it if it is necessary.

we will learn the difference between rest and spread operator in JavaScript.

Rest Parameters ( … )

Rest parameters help us to pass an infinite number of function arguments.

Example:

function sum(a,b,...remaining){     console.log(a);     console.log(b);     console.log(remaining);}sum(1,2,3,4,5,6,7);//a -> 1//b - > 2//remaining - > [3,4,5,6,7]

In the above code, the sum function accepts three arguments a, b and remaining.where the first two arguments values are 1, 2 everything we passed after is represented as an array [3,4,5,6,7].

Spread operator

Spread operator helps us to expand the strings or array literals or object literals.

  • Splitting the strings
 let name = "JavaScript"; let arrayOfStrings = [...name]; console.log(arrayOfStrings); // Ouptut -> ["J", "a", "v", "a", "S", "c", "r", "i", "p", "t"]

In the above example, we are using … spread operator to split the single string into an array of strings.

  • Merging arrays
const group1 = [1,2,3];const group2 = [4,5,6];const allGroups = [...group1,...group2];console.log(allGroups)//output -> [1, 2, 3, 4, 5, 6]

In the above code, we combined group1 and group2 by using the spread operator.

  • Merging Objects
const obj1 = {      a: 1,      b: 2}const obj2 = {      c: 3,      d: 4}const merge  = {...obj1, ...obj2};console.log(merge); // {a:1, b:2, c:3, d:4}

Using Spread operator in Function calls

We can use the spread operator to pass an array of numbers as a individual function arguments.

function sum(a,b,c){    return a+b+c;}const nums = [1,2,3];//function callingsum(...nums) // 6

Summary

  • If you see (…) dots on the function call then it is a spread operator.
  • If you see (…) dots on the function parameter then it is a rest parameter.
  • Spread operator helps us to merge Arrays or Objects.

Hope this code and post will helped you for implement The difference between Rest and spread operator in JavaScript. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US