Differentiate between the rest and spread operators in javascript

The rest and spread operators are both features introduced in JavaScript ES6 that allow for more flexible handling of arrays and objects.

  1. Rest Operator:

The rest operator is denoted by three dots (…) and is used to represent an indefinite number of arguments as an array. It is typically used in function parameters to gather all remaining arguments into an array.

Example:

function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // Output: 15

In the above example, the rest operator ...numbers gathers all the arguments passed to the sum function into an array called numbers. This allows us to pass any number of arguments to the function and perform operations on them as an array.

  1. Spread Operator:

The spread operator is also denoted by three dots (…) and is used to unpack elements from an array or object. It allows us to spread the elements of an array or object into another array or object.

Example:

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combinedArray = [...arr1, ...arr2];
console.log(combinedArray); // Output: [1, 2, 3, 4, 5, 6]

In the above example, the spread operator ...arr1 and ...arr2 spread the elements of arr1 and arr2 into a new array called combinedArray. This allows us to concatenate arrays easily without modifying the original arrays.

The spread operator can also be used to create a copy of an array or object:

const originalArray = [1, 2, 3];
const copiedArray = [...originalArray];
console.log(copiedArray); // Output: [1, 2, 3]

In this example, the spread operator ...originalArray spreads the elements of originalArray into a new array called copiedArray, creating a shallow copy of the original array.

Overall, the rest operator is used to gather multiple function arguments into an array, while the spread operator is used to spread elements from an array or object into another array or object. Both operators provide powerful ways to manipulate arrays and objects in JavaScript.