How does spread/rest operators work internally in JavaScript?

The spread and rest operators in JavaScript are two powerful features introduced in ES6 that allow developers to work with arrays and objects more conveniently.

Spread Operator

The spread operator is represented by three dots (i.e., ...) and allows an iterable (such as an array or string) to be expanded in places where zero or more arguments or elements are expected. It is commonly used for:

  • Combining arrays
  • Copying arrays
  • Constructing function arguments

Rest Operator

The rest operator is also represented by three dots (i.e., ...) and is used to gather a variable number of arguments into an array. It is often used in function definitions when you do not know how many arguments will be passed. It helps create more flexible functions.

Example

// Spread operator example const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; const combined = [...arr1, ...arr2]; console.log(combined); // [1, 2, 3, 4, 5, 6] // Rest operator example function sum(...numbers) { return numbers.reduce((acc, num) => acc + num, 0); } console.log(sum(1, 2, 3, 4)); // 10

keywords: spread operator rest operator JavaScript ES6 arrays functions