JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

How is the rest operator used in JavaScript functions?

Asked on Jul 17, 2024

Answer

The rest operator in JavaScript functions allows you to represent an indefinite number of arguments as an array. It's useful for handling function parameters when the number of arguments is not fixed.
<!-- BEGIN COPY / PASTE -->
        function sum(...numbers) {
            return numbers.reduce((total, num) => total + num, 0);
        }

        console.log(sum(1, 2, 3, 4)); // Output: 10
        <!-- END COPY / PASTE -->
Additional Comment:
  • The rest operator is represented by three dots "..." followed by a variable name.
  • In the example, "numbers" is an array containing all the arguments passed to the "sum" function.
  • The "reduce" method is used to sum up all the numbers in the "numbers" array.
  • The rest operator must be the last parameter in a function's parameter list.
✅ Answered with JavaScript best practices.
← Back to All Questions