How to create a function that accepts an unknown number of arguments in JavaScript

OpenJavaScript 0

Last updated: December 12, 2023.

Most often when defining a function, you are aware of how many arguments the function should accept:

function add(x, y) {
    return x + y;
};

add(1, 2); // Returns 3

The number of arguments accept can be extended manually:

function add(x, y, z=0) {
    return x + y + z;
};

add(1, 2); // Returns 3

add(1, 2, 3); // Returns 6

But this solution isn't very scalable because you have to include a parameter in the function for each argument you may pass in when the function is called.

A solution is to define parameters using the spread operator. The actual values passed in when the function is called are then available inside the function in array format:

function add(...numbers) {
    console.log(numbers); // [1, 1, 1, -1]
};

add(1,1,1,-1);

You can then iterate through the array to add the numbers together:

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

add(1,1,1,-1); // returns 2

You can use the same approach to join an unknown number of strings:

function joinStrings(...strings) {
    return strings.join(' ');
};

joinStrings("Hi", "how", "are", "you"); // returns 'Hi how are you'