JavaScript: Pass an Array to a Function as Multiple Arguments

Updated: March 10, 2023 By: Frienzied Flame Post a comment

This succinct, straight-to-the-point article shows how to pass an array to a function as multiple arguments. You will also learn a useful technique to define a function that can take an arbitrary number of arguments as an array.

Passing an Array to a Function

In JavaScript, the spread operator can be used to expand the elements of an array into individual arguments of a function. Therefore, we can use it to pass an array to a function as more than one argument (in my opinion, this is the best approach).

Example:

const concatenateStrings = (str1, str2, str3) => {
  return str1 + ' ' + str2 + ' ' + str3;
};

const strings = ['Welcome to', 'Sling', 'Academy'];

// call the function with the spread operator
const result = concatenateStrings(...strings);

console.log(result);

Output:

Welcome to Sling Academy

Defining a function that can take an arbitrary number of arguments

In scenarios where you want to define a function that can take an arbitrary number of arguments as an array, you can use the rest parameter syntax (…) before the parameter name in the function definition. This will collect all the remaining arguments into an array that you can access inside the function. Let’s see some real-world use cases of this technique.

Example: Sum Calculation

In this example, we will define a function that can take an arbitrary number of arguments
as an array, then calculate the sum:

const sum = (...numbers) => {
  let total = 0;
  for (let num of numbers) {
    total += num;
  }
  return total;
}

// Calling the function with different numbers of arguments
console.log(sum(1, 2, 3)); 
console.log(sum(4, 5, 6, 7, 8, 9, 100, 102));
console.log(sum(6)); 
console.log(sum());

Output:

6
241
6
0

Example: DOM manipulation

Another real-world use case is DOM manipulation. We can create a function that can take an arbitrary number of elements and add a class to each one:

function addClass(className, ...elems) {
  elems.forEach(elem => elem.classList.add(className));
}

const elem1 = document.querySelector("#elem1");
const elem2 = document.querySelector("#elem2");

addClass("my-class", elem1, elem2);

Example: Logging

In this example, we will define a logging function that can take an arbitrary number of arguments and log them to the console:

function log(...args) {
  console.log(...args);
}

log("Sling", "Academy", "welcome", "you); 
log(1, 2, 3, 4, 5); 

Output:

Sling Academy welcomes you
1 2 3 4 5

This tutorial ends here. Happy coding, and have a nice day!