...spread and ...rest in JavaScript🤔

...spread and ...rest in JavaScript🤔

We'll understand the difference between ...spread and ...rest and how they are used

·

5 min read

What is the difference between spread and rest operators?

Taking the first glance at the cover image of the title, we get an idea that the spread operator basically breaks up an entity into individual items whereas the rest operator combines up individual elements.

Talking up more formally here, spread syntax looks exactly like rest syntax. But spread syntax is the opposite of rest syntax. The main difference between them is that spread syntax "expands" an array into its individual elements, while rest syntax collects multiple elements and "condenses" them into a single element.

...spread operator

The Spread syntax can be used when all elements from an object or array need to be included in a new array or object, or should be applied one by one in a function call's arguments list. Everthing in JavaScript is considered as object, but only iterable objects can be used with spread operator

 const arr1 = ['JavaScript', 1, 2 , 'React Js', true, undefined];
 // using the whole array as single entity.
 console.log(arr1);
 // expanding the array into individual elements. 
 console.log(...arr1);

Look at the output and see the difference between their prints on the console.

image.png

Let's take a string concatenation example.

const concat = (str1, str2 ,str3) => {
    console.log(str1 + ' ' + str2 + ' ' + str3);
}
// simple approach
concat('I', 'write', 'code');
// using spread

const words = ['I', 'write', 'code'];
concat(...words);
// The output of both will be the same

Output:

image.png

Use Cases

  • Function Arguments
  • Array Operations
  • Objects

Function Arguments

Using spread to pass an array as individual elements to function as arguments.

**Example to find the sum of numbers.**

const findSum = (val1, val2, val3) => {
    return val1 + val2 + val3;
}

const numArr = [4, 8 ,6];
const sum = findSum(...numArr);
console.log(sum) // 18

Example to create users in login/signup scenario.

const user = function(name, email, password){
    this.name = name;
    this.email = email;
    this.password = password;
}
const user1 = ["Deepak", "ds038177@gmail.com", "iwritecode"];
const person1 = new user(...user1);
console.log(person1);

Output:

image.png

Array Operations

The spread operator is really helpful with arrays in copying and concatenating the arrays.

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6, ...arr1, 8 ];
console.log(arr2); // [ 4, 5, 6, 1, 2, 3, 8 ]

const arr3 = [...arr1, ...arr2];
console.log(arr3); // [ 1, 2, 3, 4, 5, 6, 1, 2, 3, 8]

We can also convert an array to an object

const arr1 = [1, 2, 3, 4, 5];
const obj1  = {...arr1};
console.log(obj1);
// Automated keys are generated

image.png

Objects

We can clone objects, create new objects by merging number of objects.

const obj1 = {
    name:'Deepak Singh',
    techStack:'JavaScript Developer',
    email:'ds038177@gmail.com'
}
console.log(obj1);

const obj2 = {
    course: 'B.Tech Cse',
    id: '200211720'
}
console.log(obj2);

const obj = {...obj1, ...obj2};
console.log(obj);

image.png

...rest operator

The rest parameter syntax allows a function to accept an indefinite number of arguments as an array, basically combining up the individual elements to form an array.

Example for finding the sum of numbers using rest operator in the function argument.

const findSum = (...elements) => {
    let sum=0;
    elements.map((element) => sum+=element);
    return sum;
}

console.log(findSum(1, 2, 3)) //6
console.log(findSum(2, 4, 8, 6, 10, 12, 14)) // 56
console.log(findSum(1, 4)) // 5

We can also spread and rest operators together,

// using rest operator
const findSum = (...elements) => {
    let sum = 0;
    elements.map((element) => sum+=element);
    return sum;
}
const arr = [2, 4, 6, 8, 10];
// using spread operator
console.log((findSum(...arr))); //30

Note: Rest is always used as a function parameter. The rest parameter has to be the last argument, as its job is to collect all the remaining arguments into an array. So having a function definition like the code below doesn’t make any sense and will throw an error.

const findSum = (a,b,...elements,c) => {
    let sum = 0;
    elements.map((element) => sum+=element);
    return a+b+c+sum;
}

console.log((findSum(2, 4, 6, 8, 10)));

image.png

We can use it with multiple arguments, but as above in error, it should be the last formal argument. The reason behind this is pretty simple and straightforward, as the rest parameter combines up the individual elements given as function arguments into an array, if there are multiple arguments present there, the values passed from the function call will be assigned to arguments by order and all remaining values will combine up in the rest parameter. If the rest parameter is not the last parameter, then there is no way to determine up to where the values should combine in the rest parameter.

const findSum = (a,b,c,...elements) => {
    let sum = 0;
    elements.map((element) => sum+=element);
    return a+b+c+sum;
}

console.log((findSum(10, 12, 2, 4, 6, 8, 10)));

Also, here is an important thing to note, only one rest parameter can be present in the function argument. The reason is the same as above, that how the values will decide to combine up in the rest parameters as there are multiple of them. It is creating obvious ambiguity here.

const findSum = (...values, ...elements) => {
    let sum = 0;
    elements.map((element) => sum+=element);
    return a+b+c+sum;
}

console.log((findSum(10, 12, 2, 4, 6, 8, 10)));

image.png

That was the brief difference between spread and rest operators and how they work in javascript. If it helps, don't forget to leave a like, and comment your feedback.

Â