Spread vs Rest Operators

it is very confusing to differentiate between the two as both have same syntax (...) .
lets look at them one by one .
Spread Operator
Expands an iterable into individual elements resulting in a new array/object with copied elements.
let array1= [1,2,4]
function sum(a,b,c){
return a+b+c
}
console.log(sum(...array1)) // 7
you can also use to make copy of arrays .
let names = [ "shay","kiya","ray"]
let newNames= ["kraven" , ...names]
console.log( newNames) //["kraven" ,"shay","kiya","ray"]
this can be used with any iterable objects .
as the name spread it spills the elements anywhere you want.
Rest Operator
Collects multiple elements/arguments into a single array. it is just opposite of what spread does . you can also look at this like other side of using ... operator .
function myFunc(...args)
{ return args; // Collects all arguments into an array
}
myFunc(1, 2, 3); // [1, 2, 3]
const [first, ...rest] = [1, 2, 3, 4, 5]; // first = 1, rest = [2, 3, 4, 5]
compiling differences
Feature | Spread Operator | Rest Operator |
Primary Function | Expands an iterable into individual elements. | Collects multiple elements/arguments into a single array. |
Common Usage | Array literals, function calls, object literals. | Function parameters, destructuring assignments. |
Position | Can be used anywhere in an array literal or function call. | Must be the last parameter in a function or destructuring pattern. |
Result | Creates a new array/object with copied elements. | Gathers remaining values into a new array or object. |






