Explain Codes LogoExplain Codes Logo

Javascript variable number of arguments to function

javascript
arguments
default-parameters
spread-operator
Anton ShumikhinbyAnton Shumikhin·Aug 19, 2024
TLDR

Harness the power of the rest operator ... in JavaScript to create adaptive functions that seamlessly deal with a multitude of arguments:

function sum(...numbers) { // Adding numbers like an accountancy pro return numbers.reduce((acc, num) => acc + num, 0); } // Liberally throwing numbers at the sum function: console.log(sum(2, 4, 6)); // Console: "I see, this equals 12"

Prefix your final parameter with ... to turn it into an all-accepting array — your own function Swiss army knife.

Embracing the arguments object

Older JavaScript code may not have had the luxury of rest parameters. Enter the arguments object. Acting like an array-like structure, it houses all the function's arguments:

function multiply() { let total = 1; for (let i = 0; i < arguments.length; i++) { // Living life on the product side total *= arguments[i]; } return total; } console.log(multiply(2, 3, 4)); // Console: "Just casually multiplying to 24"

Molding dynamic arguments

When your situation calls for more sophistication, think default values and optional parameters. Context objects and default parameters have got your back:

function greet({name = 'Guest', greeting = 'Hello'} = {}) { // I greet, therefore I am console.log(`${greeting}, ${name}!`); } greet({name: 'Alice', greeting: 'Hi'}); // Hi Alice, nice to JavaScript you!

🎨 Painting With Arguments 🖌️

Envision a function as an artist. Arguments are the gamut of paint colors at its disposal:

**Function Artist**:

```javascript
function artGallery(...colors) {
  let masterpiece = '🖼️ [ ';
  for (const color of colors) {
    // Adding a touch of color magic
    masterpiece += `${color} 🎨, `;
  }
  return masterpiece + ']';
}

Painting with singular, duos, trios, or more colors:

// Three cool cats walk into an art gallery artGallery('🔴', '🟢', '🔵'); // 🖼️ [ 🔴 🎨, 🟢 🎨, 🔵 🎨, ] // The more, the artsier artGallery('🟡', '🟣', '🟤', '⚫', '⚪'); // 🖼️ [ 🟡 🎨, 🟣 🎨, 🟤 🎨, ⚫ 🎨, ⚪ 🎨, ]

The masterpiece transforms based on the number (and choice) of colors, much like a JavaScript function altering its behavior based on the number of arguments.

Dealing with varied parameters

Calling in the spread operator

The spread operator ... unfurls an array in spots expecting zero or more arguments. It plays well with rest parameters and makes array-to-arguments conversion a breeze:

function invitees(...names) { console.log(`Invitees: ${names.join(', ')}`); } const people = ['Alice', 'Bob', 'Charlie']; invitees(...people); // Console: "Invitees: It's a party with Alice, Bob, Charlie"

Rolling out your extend methods

Should you handle option objects combining a set of default values and user-defined options, use a custom extend method as a substitute for a library function, namely $.extend from jQuery:

function extend(defaults, options) { for (let key in options) { if (options.hasOwnProperty(key)) { // Because an object's own properties matter defaults[key] = options[key]; } } return defaults; } const myOptions = extend({color: 'blue', size: 'medium'}, {size: 'large'}); console.log(myOptions); // Console: "I'm feeling blue, in a large sort of way"

Dancing with dynamic named parameters

Named parameters can be effectively managed with destructuring and default values, allowing the creation of functions that can deal with varying and flexible configurations:

function configure({settingA = true, settingB = false} = {}) { console.log(`Setting A: ${settingA}, Setting B: ${settingB}`); } configure({settingB: true}); // Console: "A true tale of two settings"