Master JavaScript Programming From Scratch

Clear, interactive, and structured JavaScript lessons designed for absolute beginners.

Spread & Rest Operators

The spread and rest operators use the same ... syntax, but they are used for different purposes in JavaScript.

What are Spread & Rest Operators?

The spread operator expands the elements of an array or the properties of an object.

The rest operator collects multiple values into a single array.

Simple Definition

Spread (...) means "expand or unpack values".

Rest (...) means "collect or pack values".

Spread vs Rest Operator Spread Operator ... [1, 2, 3] → 1, 2, 3 Expands / Unpacks Rest Operator ... 1, 2, 3 → [1, 2, 3] Collects / Packs Same ... syntax • Different purpose

Spread expands values, while Rest collects values.

Spread vs Rest

Feature Spread Rest
Syntax ... ...
Purpose Expands values Collects values
Common Use Arrays / Objects Function parameters
Direction Unpack Pack

Example 1: Spread with Arrays

The spread operator can copy the elements of one array into another array.

let numbers = [10, 20, 30];

let newNumbers = [...numbers, 40, 50];

console.log(newNumbers);
[10, 20, 30, 40, 50]

Example 2: Combining Arrays

let first = [1, 2, 3];
let second = [4, 5, 6];

let combined = [...first, ...second];

console.log(combined);
[1, 2, 3, 4, 5, 6]

Example 3: Spread with Objects

let student = {
    name: "Rahul",
    age: 22
};

let updatedStudent = {
    ...student,
    course: "JavaScript"
};

console.log(updatedStudent);
name: Rahul
age: 22
course: JavaScript

Example 4: Rest Parameters

Rest parameters collect multiple arguments into an array.

function sum(...numbers) {

    let total = 0;

    for (let number of numbers) {
        total = total + number;
    }

    return total;
}

console.log(sum(10, 20, 30));
60

Example 5: Rest with First Parameter

function showStudent(name, ...subjects) {

    console.log("Name:", name);
    console.log("Subjects:", subjects);
}

showStudent("Amit", "JavaScript", "HTML", "CSS");
Name: Amit
Subjects: JavaScript, HTML, CSS
Important Points

• Spread operator expands or unpacks values.

• Rest operator collects multiple values.

• Both use the ... syntax.

• Rest parameters are commonly used in functions.

Summary

The spread operator is useful for expanding arrays and objects, while the rest operator is useful for collecting multiple values into an array. Both use the same three-dot ... syntax.