JAVASCRIPT

What is spread and rest operator?

In JavaScript, both the spread and rest operators use the same syntax ... but they serve different purposes depending on the context.


🔹 Spread Operator (...)

The spread operator is used to expand (spread out) elements of an iterable (like an array, string, or object) into individual elements.

✅ Examples:

  1. Array Expansion
const arr = [1, 2, 3];
const newArr = [...arr, 4, 5]; 
console.log(newArr); // [1, 2, 3, 4, 5]
  1. Object Expansion
const obj1 = {a: 1, b: 2};
const obj2 = {...obj1, c: 3};
console.log(obj2); // {a: 1, b: 2, c: 3}
  1. Function Arguments
function sum(a, b, c) {
  return a + b + c;
}
const nums = [1, 2, 3];
console.log(sum(...nums)); // 6

👉 Spread is about unpacking data.


🔹 Rest Operator (...)

The rest operator is used to collect (gather) multiple elements into a single array/object.

✅ Examples:

  1. Function Parameters
function sum(...numbers) {
  return numbers.reduce((acc, num) => acc + num, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
  1. Object Destructuring
const {a, b, ...rest} = {a: 1, b: 2, c: 3, d: 4};
console.log(a);     // 1
console.log(b);     // 2
console.log(rest);  // {c: 3, d: 4}
  1. Array Destructuring
const [first, ...others] = [10, 20, 30, 40];
console.log(first);   // 10
console.log(others);  // [20, 30, 40]

👉 Rest is about packing data.


🎯 Key Difference

  • Spread (...)Expands elements (unpacks).
  • Rest (...)Collects elements (packs).

⚡Quick way to remember:
👉 Spread = Expand
👉 Rest = Collect/Condense

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *