Difference between rest and spread?

I m going through spread operator exercise but very confused over a statement which says

...arr returns an unpacked array. In other words, it spreads the array. However, the spread operator only works in-place, like in an argument to a function or in an array literal. The following code will not work:

I have checked forums as well here, and here , but can;t understand it.

It seems to spread and rest are same i.e. they unpack the an argument which should be array?

Yeah, I think it’s a little confusing that the same operator gets used for two different things. I mean we do that with others: a + can mean addition (numbers) or concatenation (strings). It can also coerce to a number (unary plus operator).

So, we have the ... that means two different things. They are somewhat related, if in opposite direction. The spread operator takes an array or object and breaks it into pieces. And the rest operator a takes leftover pieces and puts them in an array or object.

Besides reading explanations, I would advice to focus on one (maybe the spread operator since I think that gets used the most) and really learn it well. Do every tutorial on and try out the code. Make up your own code. Watch all the videos. Learn it really well. Then take a look at the other one.

And go easy on yourself - this is hard stuff.

Hello @mahassan!

From my understanding, the spread operator is used to ‘spread’ or distrubute array values into many arguments.

For example:

const nums = [1, 2, 3, 4];

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

sum(...nums) 
// console.log to see the answer
// which should be 10

The rest operator meanwhile takes the arguments of a function and condenses it into a single array.

For example:

function sum(...nums){

let result = 0;
for (const num of nums){
result += num;
}

return result;
};

sum(8,1,4,5);
// the function will first condense your arguments to a single array [8, 1, 4, 5]
// using a loop, we can then iterate over these args and add them to our result
// result should be 18 if console logged

If you find the code I had typed above messy, I’m sorry… I am actually typing this on my phone and if you found any errors, you can modify the examples to your understanding.

Hoped this helped.

Thanks everyone, I think I am starting to under. but in the link, there is an example


SEPTEMBER 15, 2021
/
#JAVASCRIPT
JavaScript Rest vs Spread Operator – What’s the Difference?
Oluwatobi Sofela
Oluwatobi Sofela
JavaScript Rest vs Spread Operator – What’s the Difference?
JavaScript uses three dots (...) for both the rest and spread operators. But these two operators are not the same.

The main difference between rest and spread is that the rest operator puts the rest of some specific user-supplied values into a JavaScript array. But the spread syntax expands iterables into individual elements.

For instance, consider this code that uses rest to enclose some values into an array:

// Use rest to enclose the rest of specific user-supplied values into an array:
function myBio(firstName, lastName, ...otherInfo) { 
  return otherInfo;
}

// Invoke myBio function while passing five arguments to its parameters:
myBio("Oluwatobi", "Sofela", "CodeSweetly", "Web Developer", "Male");

// The invocation above will return:
["CodeSweetly", "Web Developer", "Male"]
Try it on StackBlitz

In the snippet above, we used the ...otherInfo rest parameter to put "CodeSweetly", "Web Developer", and "Male" into an array.

Now, consider this example of a spread operator:

// Define a function with three parameters:
function myBio(firstName, lastName, company) { 
  return `${firstName} ${lastName} runs ${company}`;
}

// Use spread to expand an array’s items into individual arguments:
myBio(...["Oluwatobi", "Sofela", "CodeSweetly"]);

// The invocation above will return:
“Oluwatobi Sofela runs CodeSweetly”
Try it on StackBlitz

In the snippet above, we used the spread operator (...) to spread ["Oluwatobi", "Sofela", "CodeSweetly"]’s content across myBio()’s parameters.

Don’t worry if you don’t understand the rest or spread operators yet. This article has got you covered!

In the following sections, we will discuss how rest and spread work in JavaScript.

So, without any further ado, let’s get started with the rest operator.

What Exactly Is the Rest Operator?
The rest operator is used to put the rest of some specific user-supplied values into a JavaScript array.

So, for instance, here is the rest syntax:

...yourValues
The three dots (...) in the snippet above symbolize the rest operator.

The text after the rest operator references the values you wish to encase inside an array. You can only use it before the last parameter in a function definition.

To understand the syntax better, let’s see how rest works with JavaScript functions.

How Does the Rest Operator Work in a Function?
In JavaScript functions, rest gets used as a prefix of the function’s last parameter.

Here’s an example:

// Define a function with two regular parameters and one rest parameter:
function myBio(firstName, lastName, ...otherInfo) { 
  return otherInfo;
}
The rest operator (...) instructs the computer to add whatever otherInfo (arguments) supplied by the user into an array. Then, assign that array to the otherInfo parameter.

As such, we call ...otherInfo a rest parameter.

Note: Arguments are optional values you may pass to a function’s parameter through an invocator.

Here’s another example:

// Define a function with two regular parameters and one rest parameter:
function myBio(firstName, lastName, ...otherInfo) { 
  return otherInfo;
}

// Invoke myBio function while passing five arguments to its parameters:
myBio("Oluwatobi", "Sofela", "CodeSweetly", "Web Developer", "Male");

// The invocation above will return:
["CodeSweetly", "Web Developer", "Male"]
Try it on StackBlitz

In the snippet above, notice that myBio’s invocation passed five arguments to the function.

In other words, "Oluwatobi" and "Sofela" got assigned to the firstName and lastName parameters.

At the same time, the rest operator added the remaining arguments ( "CodeSweetly", "Web Developer", and "Male") into an array and assigned that array to the otherInfo parameter.

Therefore, myBio() function correctly returned ["CodeSweetly", "Web Developer", "Male"] as the content of the otherInfo rest parameter.

Beware! You Cannot Use “use strict” Inside a Function Containing a Rest Parameter
Keep in mind that you cannot use the “use strict” directive inside any function containing a rest parameter, default parameter, or destructuring parameter. Otherwise, the computer will throw a syntax error.

For instance, consider this example below:

// Define a function with one rest parameter:
function printMyName(...value) {
  "use strict";
  return value;
}

// The definition above will return:
"Uncaught SyntaxError: Illegal 'use strict' directive in function with non-simple parameter list"
Try it on CodeSandbox

printMyName() returned a syntax error because we used the “use strict” directive inside a function with a rest parameter.

But suppose you need your function to be in strict mode while also using the rest parameter. In such a case, you can write the “use strict” directive outside the function.

Here’s an example:

// Define a “use strict” directive outside your function:
"use strict";

// Define a function with one rest parameter:
function printMyName(...value) {
  return value;
}

// Invoke the printMyName function while passing two arguments to its parameters:
printMyName("Oluwatobi", "Sofela");

// The invocation above will return:
["Oluwatobi", "Sofela"]
Try it on CodeSandbox

Note: Only place the “use strict” directive outside your function if it is okay for the entire script or enclosing scope to be in strict mode.

So now that we know how rest works in a function, we can talk about how it works in a destructuring assignment.

How the Rest Operator Works in a Destructuring Assignment
The rest operator typically gets used as a prefix of the destructuring assignment’s last variable.

Here’s an example:

// Define a destructuring array with two regular variables and one rest variable:
const [firstName, lastName, ...otherInfo] = [
  "Oluwatobi", "Sofela", "CodeSweetly", "Web Developer", "Male"
];

// Invoke the otherInfo variable:
console.log(otherInfo); 

// The invocation above will return:
["CodeSweetly", "Web Developer", "Male"]
Try it on StackBlitz

The rest operator (...) instructs the computer to add the rest of the user-supplied values into an array. Then, it assigns that array to the otherInfo variable.

As such, you may call ...otherInfo a rest variable.

Here’s another example:

// Define a destructuring object with two regular variables and one rest variable:
const { firstName, lastName, ...otherInfo } = {
  firstName: "Oluwatobi",
  lastName: "Sofela", 
  companyName: "CodeSweetly",
  profession: "Web Developer",
  gender: "Male"
}

// Invoke the otherInfo variable:
console.log(otherInfo);

// The invocation above will return:
{companyName: "CodeSweetly", profession: "Web Developer", gender: "Male"}

so my confusion is

  • How can we console.log(otherInfo) from a destructing

that is totally new thing for me.

Do you mean how can it print multiple things? (It isn’t actually doing destructing, just printing what is in otherinfo, which is an array).

Because that spread operator created an object called “otherInfo”.

This:

const { firstName, lastName, ...otherInfo } = someObject;

says:

If someObject has properties firstName and lastName, store those in those variable names. Everything leftover (the “rest”), store it in an object called “otherInfo”.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.