Spread & Rest | Dataplexa

Spread & Rest Operators

As JavaScript applications grow, we often work with arrays, objects, and functions that handle many values.

Spread and Rest operators, introduced in ES6, make this work cleaner and more flexible.


Understanding the ... Syntax

Both spread and rest operators use the same syntax:

...

What changes is how and where the syntax is used.


Spread Operator

The spread operator is used to expand elements from an array or object.

It takes values out and spreads them into a new place.


Spread with Arrays


let numbers = [1, 2, 3];
let newNumbers = [...numbers, 4, 5];
  

This creates a new array without modifying the original one.


Why Spread Is Useful

Before ES6, copying arrays often caused bugs because references were shared.

Spread helps create safe copies.


Spread with Objects

Spread can also be used with objects.


let user = { name: "Alex", role: "Admin" };

let updatedUser = {
  ...user,
  role: "Editor"
};
  

Only the changed property is updated.


Rest Operator

The rest operator is used to collect multiple values into a single variable.

It is commonly used in function parameters.


Rest in Functions


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

This function can accept any number of arguments.


Real-World Example

Handling multiple user inputs dynamically:


function logActions(...actions) {
  actions.forEach(action => {
    console.log(action);
  });
}
  

Rest allows flexibility without complex logic.


Spread vs Rest

  • Spread expands values
  • Rest collects values
  • Both use the same ... syntax

Common Beginner Mistakes

  • Confusing spread with rest
  • Using rest outside function parameters
  • Overusing spread unnecessarily

Understand the context before using ....


Thumb Rules

  • Use spread to copy or merge data
  • Use rest to handle variable arguments
  • Avoid mutating original arrays or objects
  • Keep code readable

What Comes Next?

Now that you can manage multiple values easily, the next step is breaking data into smaller parts.

In the next lesson, we will learn about destructuring.