JavaScript Spread vs. Rest Operator

Introduction

In modern JavaScript, the spread and rest operators are indispensable tools for simplifying array manipulation and function parameters. These operators provide elegant solutions for tasks like array expansion and handling function arguments.

Let’s dive deeper into understanding how they work so you can leverage their power.

The Spread Operator

The spread operator, denoted by three consecutive dots (…), is primarily used in expanding iterable variables like arrays into individual elements. This operator allows us to merge, copy or pass array elements to functions without explicitly iterating through them.

let arr = [2, 4, 6];
console.log(array);

// Expanding an array
let newArr1 = [8, ...arr]; // output: 8, 2, 4, 6
let newArr2 = [...arr, 8]; // ouptut: 2, 4, 6, 8

// Combining arrays
const arr1 = [1, 3, 5, 7, 9];
const arr2 = [2, 4, 6, 8];
const combinedArr = [...arr1, ...arr2]; // output: 1, 3, 5, 7, 9, 2, 4, 6, 8

// Passing arguments to Functions
function sum(a, b, c) {
  return a + b + c;
}

const numbers = [1 , 2, 3];
const result = sum(...numbers); // instead of: sum(numbers[0], numbers[1], numbers[2])

// Copying arrays
const origArr = [2, 4, 6, 8];
const copiedArr = [...origArr];

The Rest Operator

While the spread operator expands elements, the rest operator condenses them into a single entity within function parameters or array destructuring. It collects the remaining elements into a designated variable, facilitating flexible function definitions and array manipulation.

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

console.log(sum(1, 2, 3, 4)); // this returns 10 (1 + 2 + 3 + 4)
console.log(sum(3, 4, 5)); // this returns 12

This operator operates very similarly to the construct called varargs in Java to pass an arbitrary number of values/parameters to a method. Read more here.

Hopefully, it will be helpful for your life.

References

[1] JavaScript Spread and Rest Operators – Explained with Code Examples, https://www.freecodecamp.org/news/javascript-spread-and-rest-operators/, accessed on 15 Oct 2024

[2] Rest vs Spread explained in JavaScript, https://www.telerik.com/blogs/rest-spread-operators-explained-javascript, accessed on 15 Oct 2024

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.