JavaScript Rest and Spread Operators

Rest Parameter

1. Rest parameter is used to accept multiple values, store them in an array, and the array's reference will be stored in the variable we used for rest.

2. Rest can accept n number of values and store them in an array.

3. To make a variable rest, we have to put '...' before the variable name.

4. Syntax: let ...variable_name;

5. We can use rest in functions when we don't know the exact number of arguments.

6. In function, there can be only one rest parameter and it should be the last parameter.

function details(a, b, ...z) {
  console.log(a); // 10
  console.log(b); // 20
  console.log(z[0]); // 30
  console.log(z[1]); // 40
  console.log(z[2]); // 50
  console.log(z[3]); // 60
  console.log(z[4]); // 70
}

details(10, 20, 30, 40, 50, 60, 70); // function call

Here, if we pass two values they will be stored in a, b respectively and further values will be stored by rest in an array. We can pass n number of values.

Uses of REST Parameter

1. REST parameter can be used in function definition parameter list to accept multiple values.

2. It can also be used in array and object destructuring.

If we pass literals to three dots (...), it will accept all literals and behave as a rest parameter.

Spread Operator

1. It is used to unpack elements from iterables (like array or object).

Use Cases:

1. Passing array elements as function arguments

let arr = [10, 2, 3, 40, 500, 6];

function sum(...data) {
  let acc = 0;
  for (let val of data) {
    acc = acc + val;
  }
  return acc;
}
let result = sum(...arr);
console.log(result); // 561

// ...data - rest parameter
// ...arr - spread operator

2. Creating a new array from existing array

We can ask the spread operator to store the unpacked elements in an array object by using spread operator inside [ ] brackets.

let new_arr = [...arr];
console.log(new_arr); // [10, 2, 3, 40, 500, 6]

3. Creating a new object from existing object

We can ask the spread operator to store the unpacked elements in an object by using spread operator inside { } brackets.

let human1 = {
  name: "Chombu",
  age: 21,
};

let human2 = { ...human1 };
console.log(human2); // { name: "Chombu", age: 21 }

4. Combining arrays or objects

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let combinedArr = [...arr1, ...arr2];
console.log(combinedArr); // [1, 2, 3, 4, 5, 6]

let obj1 = { a: 1, b: 2 };
let obj2 = { c: 3, d: 4 };
let combinedObj = { ...obj1, ...obj2 };
console.log(combinedObj); // { a: 1, b: 2, c: 3, d: 4 }

5. Converting string to array

let str = "hello";
let chars = [...str];
console.log(chars); // ["h", "e", "l", "l", "o"]

If we do not pass literals to three dots (...), it will unpack all literals and behave as a spread operator.

Key Differences Between Rest and Spread