Rest Parameter in JavaScript

  • In JavaScript, the rest parameter is a feature that allows you to represent an indefinite number of arguments as an array in a function declaration. This means that you can pass any number of arguments to the function, and they will be captured and stored as an array in the rest parameter.
  • The rest parameter is denoted by three dots (...) followed by the parameter name, and it must be the last parameter in the function declaration. Here's an example:

    function sum(...numbers) {
        let total = 0;
        for (let number of numbers) {
            total += number;
        }
        return total;
    }

    sum(1, 2, 3); // returns 6
    sum(4, 5, 6, 7); // returns 22

  • In this example, the sum() function has a rest parameter numbers, which collects any number of arguments passed to the function and stores them as an array. Inside the function, we can use a loop to iterate over the array and add up all of the numbers.
  • Rest parameters are particularly useful when you need to write a function that can accept a variable number of arguments or when you don't know how many arguments will be passed in advance. By using the rest parameter, you can avoid having to list out all of the arguments as parameters in the function declaration, making the code more concise and easier to read.

No comments:

Post a Comment

Primitive Types in TypeScript

In TypeScript, primitive types are the most basic data types, and they are the building blocks for handling data. They correspond to simple ...