JavaScript·100 questions

QUESTION: What are spread and rest?

Answer

The spread and rest operators in JavaScript are written identically as three dots, but perform opposite tasks depending on the context of their usage. They significantly simplify manipulations with data sets and collections.

The spread operator acts as an unpacker, expanding iterable objects such as arrays or strings into individual elements. With its help, you can easily combine arrays, creating new collections from the elements of old ones.

Also, spread is actively used for cloning and supplementing objects with new keys and values in literal form, replacing outdated data merging methods.

The rest operator, on the other hand, acts as a collector that combines multiple disparate arguments into a single array. This is especially useful when creating functions with a variable number of parameters.

When the exact number of arguments is not known in advance, it is convenient to intercept them via a rest parameter in the function signature to process them as a standard array.

Use three dots before the array name to unpack it using the spread operator.
Apply spread in an object literal to add new properties to existing ones.
Specify three dots before the parameter name in a function to collect arguments via rest.
Combine rest during destructuring to collect remaining elements into a separate array.

The same mechanism of successful data collection is also applied inside destructuring. There, you can take the first element of an array into a separate variable and pack the rest into a new array using the rest syntax.

Was this answer helpful?

More questions in this topic

Related questions from other topics