Sling Academy
Home/JavaScript/JavaScript: Pass an Array to a Function as Multiple Arguments

JavaScript: Pass an Array to a Function as Multiple Arguments

Last updated: March 10, 2023

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!

Next Article: JavaScript: 3 Ways to Create Multidimensional Arrays

Previous Article: JavaScript: 4 Ways to Swap Elements in an Array

Series: Working with Arrays in JavaScript

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration