JavaScript - How to use rest parameters and spread syntax?

Rest and spread is a very useful feature for handling variable number of arguments in a function.

What is arguments inside a function?

arguments contains information about all the parameters being passed to a function. Don’t make mistake of understanding it as an array. It is an object of type Arguments

Let’s take the following code block as an example

    function getFuncArguments() {
        // arguments is of type Arguments, not exactly an array
        return arguments;
    }
    const normalArray = [1, 3, 'a'];

    console.log(getFuncArguments(1, 3, 'a'))
    // [Arguments] { '0': 1, '1': 3, '2': 'a' }
    console.log(getFuncArguments(...normalArray));
    // [Arguments] { '0': 1, '1': 3, '2': 'a' }
    console.log(getFuncArguments(normalArray));
    // [Arguments] { '0': [ 1, 3, 'a' ] }

Technically, arguments could be used to solve the problem of multiple arguments in a function. But it would make the code very messy and unreadable.

A practical example and use of spread operator (...normalArray) could also be seen above.

Realtime use of rest parameter & spread syntax

Take the following code block as en example. The requirements for the findMinimum function are - Minimum two parameters are required to call the function. - It should be possible to pass variable number of other arguments - It should find the minimum value for the input parameters

const numbers = [2, 3, 5, 6]

// same as findMinimum(10, 20, 2, 3, 5, 6)
let minValue = findMinimum(10, 20, ...numbers);

console.log(`Minimum of all numbers is ${minValue}`);

function findMinimum(first, second, ...rest) {
    // rest is an array
    console.log(rest);
    //Above would print [2, 3, 5, 6 ]

    // const spreadTheRest = ...rest; Not allowed

    // combine all input in one array
    // The array rest is spread 
    const inputsWithSpread
        = [first, second, ...rest];
    console.log(inputsWithSpread);
    // above would print [ 2, 3, 5, 6 ]
    const inputsWithoutSpread
        = [first, second, rest];
    console.log(inputsWithoutSpread);
    //Above would print [ 10, 20, [2, 3, 5, 6 ] ]

    let min = first;
    for (const item of inputsWithSpread) {
        if (item < min) { min = item; }
    }
    return min;
}

The spread and rest syntax are exactly same but they are opposite of each other.

Comments