The three dots ... in JavaScript do two completely different jobs depending on where you use them. When you spread, you unpack a collection. When you rest, you collect leftovers into one. Same syntax, opposite directions β and once you see the difference, you will use both everywhere.
Spread unpacks an array or object into individual pieces. It is the cleanest way to copy an array, merge objects, or pass array items as function arguments.
const nums = [ 1 , 2 , 3 ] ; const more = [ . . . nums , 4 , 5 ] ; // [1, 2, 3, 4, 5]
const user = { name : "Arhan" , age : 22 } ; const updated = { . . . user , age : 23 } ; // age updated, original untouched
console . log ( Math . max ( . . . nums ) ) ; // 3
Enter fullscreen mode
Exit fullscreen mode
Rest does the reverse: it gathers remaining items into a single array or object. You see it most often in function parameters and destructuring.
function sum ( first , . . . rest ) { return rest .β¦