DEV Community

Cover image for Spread and Rest operator in JS
SAIFULLAH🇮🇳
SAIFULLAH🇮🇳

Posted on

Spread and Rest operator in JS

Make your JavaScript code cleaner and less complex with spread & rest operators.

Unlock the power of spread and rest operators in JavaScript:

Spread and Rest operators **are two important features in JavaScript introduced in **ECMAScript 6 (ES6) that provide a concise and powerful way to work with arrays and objects.

1. Spread Operator

_The spread operator (…) _is used to spread the contents of an array or object into individual elements. This is useful when you want to combine multiple arrays or objects into a single array or object, Or when passing arrays or objects as arguments.

We can also use the spread operator to add new elements to an array:
Spread operator

In the example below, we use the spread operator to add the element 0 to the beginning of the arr array.

Image eg

The spread operator can also be used with objects.

2. Rest Operator

The rest operator (…) is used to represent an indefinite number of arguments as an array. This is useful when you want to pass a variable number of arguments to a function, or when you want to group a set of arguments into an array.

In this example, we define a function called sum that uses the rest operator to collect any number of arguments into an array called numbers. We then use the reduce method to sum up the numbers in the array and return the result.

Image
We can also use the rest operator to group a set of arguments into an array.
So must use this two operators to ease your code.

That's it!
Thanks for reading 🙌

Top comments (0)