Menu

Spread and Rest Operators in JavaScript: One Syntax, Two Jobs
πŸ“°

Spread and Rest Operators in JavaScript: One Syntax, Two Jobs

DEV Community: frontendΒ·Arhan KhanΒ·about 18 hours ago
#qVHKzGe6
#devtofrontend#devto#dev#copy#const
Long article (395 words) β€” no AI summary yet.
Reading 0:00
15s threshold

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 .…

Continue reading β€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.