Rest Operator in Javascript

After explaining the spread operator (you can check all about it in the link below), it's time to demystify the rest (...) operator. The two look exactly the same but they serve different functions. One thing they have in common, besides the identical syntax, is that they work with iterables like arrays, objects, sets or maps.

The rest operator collects all remaining elements into an array or into an object. It can be used for destructuring or handling function parameters, especially when their number is unknown.

1. Object destructuring. In the example below we can see destructuring in action. All the properties we didn't want to put into individual variables are now stored into a separate object. We can access the properties of that object using the dot notation.


        <script>

            const myDoggo = {
            name: 'Twister',
            age: 5,
            breed: 'Labrador',
            favoriteToy: 'shoes',
            favoriteFood: 'anything goes',
            favoriteActivity: 'sleeping'
            }


            const {name, age, favoriteToy, ...otherProperties} = myDoggo;
            console.log(name); // prints Twister
            console.log(age); // prints 5
            console.log(favoriteToy); // prints shoes
            console.log(otherProperties) // prints {breed: 'Labrador',             favoriteFood: 'anything goes', favoriteActivity: 'sleeping' }
            console.log(otherProperties.breed) // prints Labrador

        </script>



We can of course do the same thing with an array. We can access the items of the array using the square bracket notation:

                <script>
           
            const randomWords = ['minute', 'delete', 'fork', 'share', 'untitled'];
            [one, two, ...rest] = randomWords;
            console.log(one); // prints minute
            console.log(two); // prints delete
            console.log(rest); // prints ['fork', 'share', 'untitled']
            console.log(rest[0]); // prints fork

        </script>

2. Function parameters handling
 The rest parameter allows us to represent an indefinite number of arguments as an array. Let's see the code below.


        <script>

            const addNumbers = (a, b) => {
            console.log(a + b)
            }

            addNumbers(34, 78, 56, 89); // returns 112

        </script>