Skip to main content

Command Palette

Search for a command to run...

Spread vs Rest Operators in JavaScript

Updated
•4 min read•View as Markdown

In JavaScript, you will often see three little dots (...) on the codebase. This syntax is a shape-shifter: depending on exactly where and how you use it, it acts as either the Spread operator or the Rest parameter.

While they look identical they do the exact opposite of each other. One unpacks values, and the other bundles them . Lets know the differences how they work with arrays and objects

The core concept

To understand the difference, remember this simple rule:

  • Spread expands elements (takes items out of a box).

  • Rest collects elements (puts items into a box).

The Spread Operator

The spread operator takes an iterable (like an array, a string, or an object) and expands it into individual elements. We use it in places where zero or more arguments or elements are expected.

Spreading with Arrays

Spread is useful for copying or merging arrays without changing the original data.

// Copying an array
const basicSpices = ['Turmeric', 'Cumin', 'Coriander'];
const spicesCopy = [...basicSpices]; 

// Merging arrays
const extraSpices = ['Garam Masala', 'Cardamom'];
const allSpices = [...basicSpices, ...extraSpices, 'Cloves'];

console.log(allSpices); 
// Output: ['Turmeric', 'Cumin', 'Coriander', 'Garam Masala', 'Cardamom', 'Cloves']

The Rest Operator

The rest operator does the exact reverse. It collects multiple independent elements and packs them into a single array (or object). It is primarily used in function definitions and destructuring.

Rest in Function Parameters

When you don't know exactly how many arguments will be passed into a function the rest parameter gathers all arguments into a array.

Important Rule: The rest parameter must always be the last parameter in the function definition.

// Collecting an unknown number of arguments
function calculateTotal(discount, ...prices) {
    // 'prices' is now an array of all arguments passed after discount
    const total = prices.reduce((sum, price) => sum + price, 0);
    return total - discount;
}

console.log(calculateTotal(50, 200, 150, 100)); 
// Output: 400 (which is 450 total - 50 discount)

Rest in Destructuring

You can extract specific items from an array or object and use rest operator to scoop up everything else that is left over.

const ranking = ['Gold', 'Silver', 'Bronze', 'Participation', 'Disqualified'];

// Extract the first two, collect the rest
const [firstPlace, secondPlace, ...others] = ranking;

console.log(firstPlace); // 'Gold'
console.log(others);     // ['Bronze', 'Participation', 'Disqualified']

Practical Real-World Use Cases

Here are some common scenarios where we will see these operators in codebases:

  1. Finding the maximum value in an array (Spread): The Math.max() function doesn't accept an array; it requires a list of numbers. Spread solves this easily.

    const temperatures = [32, 41, 28, 45, 39];
    const hottest = Math.max(...temperatures); // Expands array into individual numbers
    
  2. Passing Props in React (Spread): If you are working with React spread is heavily used to pass an entire object of properties to a component at once.

    const userDetails = { name: "Anita", age: 28, role: "Admin" };
    <UserProfile {...userDetails} />
    
  3. Removing a specific property from an object (Rest): You can use rest destructuring to create a new object without a specific, unwanted property (like a password).

    const userRecord = { id: 101, username: "admin", password: "superSecretPassword123" };
    
    // Extract password, bundle the rest into a 'safeUser' object
    const { password, ...safeUser } = userRecord;
    
    console.log(safeUser); 
    // Output: { id: 101, username: "admin" }
    

Summary of Differences: Spread vs Rest

Here is a table to help you differentiate between them

Feature

Spread Operator (...)

Rest Parameter (...)

Main Function

Unpacks elements into individual pieces.

Packs elements into a single array/object.

Commonly used in

function calls, array literals, or object literals.

function declarations or destructuring assignments.

Positioning

Can be used anywhere within the array/object.

Must be the very last variable or parameter.

Mental Model

Taking items out of a suitcase and laying them on a bed.

Sweeping items off a desk into a single trash bin.

So, refer to table and hope you got to know the differences and usecases of them.

Thanks for Reading.