JavaScript Spread & Rest Operators

By Dillon Smart · · · 0 Comments

JavaScript Spread & Rest Operators

In JavaScript, three dots ( … ) are used for both the Spread and Rest operators. Spread and Rest perform different actions. Let’s learn what the JavaScript Spread & Rest Operators do.

JavaScript Spread Operator

The JavaScript Spread Operator ( … ) allows us to copy and split an Array or Object into another Array or Object.

Let’s look at an example of the Spread Operator in use:

const numbers = [1, 2, 3];
const newNumbers = [4, 5, 6];
const joinNumbers [...numbers, ...newNumbers];

console.log(joinNumbers);
// Output: [1, 2, 3, 4, 5, 6]

JavaScript Rest Operator

In JavaScript, the Rest Operator is used in a very different way to the Spread Operator. The Rest Operator puts the rest of some specific values into an array.

What does this mean?

The Rest Operator allows a function to accept an indefinite number of arguments as an array.

Let’s look at an example of the Rest Operator in use:

function sumOfNumbers(...numbers) {
    let value = 0;
    for(const num of numbers) {
        total += num;
    }
    return total;
}

console.log( sumOfNumbers(1, 2, 3) );
// Output: 6

console.log( sumOfNumbers(5, 10, 15, 20) );
// Output: 50

Conclusion

The JavaScript Spread & Rest Operators can prove to be very useful for your web applications.

Learn about Destructuring in JavaScript.

JavaScript

0 Comment

Was this helpful? Leave a comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Angular Material Dialog

Updated 16th August 2022

Angular is an awesome framework, yet it does have a steep learning curve for many developers. This post is aimed at those with experience using Angular 2/4/5 who want to use the Angular Material Dialog. This post will assume you have already installed the @angular/material library. If you have I would refer you to take

Vue 3 Popup Modal Component – Create a Modal

Updated 23rd August 2022

In this post, I’m going to show you how to create a Popup Modal Component in Vue 3. This Popup Modal will use the built-in transition component. The Modal we will create looks a lot like the Modal Dialogs used by Apple in iOS. We will use Tailwind CSS for styling. What is Vue?  Vue

Destructuring in JavaScript

Updated 16th August 2022

Introduced in ES6, Destructuring in JavaScript is a way to unpack values from arrays, or properties from objects, into distinct variables. What is a use-case of Destructuring in JavaScript? Until ES6, if we wanted to extract data from an array we would have to do something similar to: let message = ; let greeting