Waiting Answer May 19, 2024

Why We Used Spread Operator and Rest Operator in JS?

In what locations we can use the spread operator and rest operator, and how it works

Answers
2024-06-09 18:01:28

Basically spread operators and rest operators syntax are same but serve different purposes. 

Spread operator:-The spread operator expands elements of an iterable (like an array or object) into individual elements.

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

Rest operator:-The rest operator collects multiple elements into a single array or object. It is often used for function parameters to handle a variable number of arguments.

Ex:-const [first, ...rest] = [1, 2, 3, 4];

console.log(first); // Outputs: 1

console.log(rest); // Outputs: [2, 3, 4

]