Spread and rest operators [...]
Introduction
Spread
and rest
operators both are a powerful feature that
makes your life easier while working with objects and arrays.
Spread Operator
The spread operator (...)
allows you to expand an iterable
(for example `array) into individual elements.
Spread in arrays
Another, real life example:
Spread in objects
Rest operator
The rest operator (...)
allows you to condense multiple elements into a single array
or object
.
Rest operator in functions
Rest in arrays
In this example the rest
operator condenses the remaining elements into the rest array
.
Combine Spread and Rest
Both spread
and rest operators
can be combined in some scenarios. Let's check example.
Best practices
-
Don't overuse!: While both are useful for code readability, as you can see while we combined them, the complexity of the code has grown a lot. Imagine more complex scenario.
-
Order: Pay attention to order when using spread and rest operators.