Skip to content

The Spread Operator (...) and the Rest Operator

Posted on:November 7, 2023 at 07:35 AM

In JavaScript, the spread operator (...) and the rest operator (...) are versatile tools for working with arrays, objects, and functions. Let’s dive into their usage and see how they can enhance your coding experience.

Spread Operator

Spreading into Arrays

The spread operator allows you to expand an iterable (like an array) into individual elements. For example:

const array = [7, 8, 9];
const newArray = [1, 2, ...array];
console.log(newArray); // Output: [1, 2, 7, 8, 9]

It can be used to copy an array as well:

const arrayCopy = [...array];

Joining Arrays

The spread operator can join multiple arrays efficiently:

const arrayFood = [...arrayFruit, ...arrayNuts];

Using the Spread Operator on Strings

It’s not limited to arrays; you can spread characters from a string:

const str = "Joe";
const letters = [...str, " ", "M."];
console.log(letters); // Output: ['J', 'o', 'e', ' ', 'M.']

Using the Spread Operator in Function Calls

You can pass an array of arguments into a function using the spread operator:

function orderPasta(ing1, ing2, ing3) {
  console.log(
    `Here is your delicious pasta with ${ing1}, ${ing2}, and ${ing3}.`
  );
}

const ingredients = ["mushrooms", "spinach", "cheese"];
orderPasta(...ingredients);

Using the Spread Operator on Objects

The spread operator can merge objects and copy them:

const newRestaurant = { foundedIn: 1998, ...restaurant, founder: "Guiseppe" };
console.log(newRestaurant);

const restaurantCopy = { ...restaurant };
restaurantCopy.name = "Ristorante Roma";
console.log(restaurantCopy.name); // Output: Ristorante Roma
console.log(restaurant.name); // Output: Classico Italiano

Rest Operator

Packing Elements into Arrays

While the spread operator unpacks elements from an array, the rest operator does the opposite; it packs elements into an array. For example:

const [a, b, ...others] = [1, 2, 3, 4, 5];
console.log(a, b, others); // Output: 1 2 [3, 4, 5]

You can use it to collect elements not assigned to specific variables.

Rest Operator with Objects

The rest operator can also be applied to objects, capturing the remaining properties:

const { sat, sun, ...weekdays } = openingHours;

Rest Operator in Functions

In function parameters, the rest operator allows you to accept an arbitrary number of arguments as an array:

const add = function (...numbers) {
  let sum = 0;
  for (let i = 0; i < numbers.length; i++) sum += numbers[i];
  console.log(sum);
};

add(2, 3);
add(5, 3, 7, 2);
add(8, 2, 5, 3, 2, 1, 4);

const x = [23, 5, 7];
add(...x);

It simplifies working with dynamic argument lists in functions.

function orderPizza(mainIngredient, ...otherIngredients) {
  console.log(
    `Here is your delicious pizza with ${mainIngredient}, ${otherIngredients}.`
  );
}
orderPizza("mushrooms", "onion", "olives", "spinach");

The spread and rest operators are valuable tools in JavaScript, offering enhanced flexibility and convenience in your code. Use them wisely to streamline your programming tasks.