It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 77 – Rest Operator in JavaScript

What You’ll Learn

  • What the rest operator is in JavaScript
  • How to use it in function parameters and array/object destructuring
  • Difference between rest and spread operators

Introduction

The rest operator (...) allows you to represent an indefinite number of arguments as an array or gather the "rest" of items in destructuring.

function showNumbers(...nums) {
  console.log(nums);
}

showNumbers(1, 2, 3); // [1, 2, 3]

Syntax and Use Cases

1. Rest in Function Parameters

function sumAll(...numbers) {
  return numbers.reduce((acc, curr) => acc + curr, 0);
}

console.log(sumAll(5, 10, 15)); // 30
  • The function accepts any number of arguments and packs them into the numbers array.

2. Rest in Array Destructuring

const colors = ["red", "blue", "green", "yellow"];

const [primary, secondary, ...others] = colors;

console.log(primary);  // "red"
console.log(secondary); // "blue"
console.log(others);   // ["green", "yellow"]
  • The rest operator groups remaining items into a new array.

3. Rest in Object Destructuring

const user = {
  name: "Amina",
  age: 25,
  country: "Ghana",
  profession: "Developer"
};

const { name, ...details } = user;

console.log(name);    // "Amina"
console.log(details); // { age: 25, country: "Ghana", profession: "Developer" }
  • Similar to arrays, the rest operator gathers leftover key-value pairs.

?Rest vs Spread

Rest Spread
Collects values into a group Spreads out elements
Used in function parameters or destructuring Used in function calls, arrays, or objects

Try Your Hand

  1. Write a function called multiplyAll() that multiplies all given numbers using rest parameters.
  2. Use array destructuring and the rest operator to extract the first two items, and collect the remaining in a new array.

Summary

  • The rest operator (...) is used to collect remaining items.
  • It works in function parameters, arrays, and objects.
  • Don’t confuse it with the spread operator, which is used to expand items.