Today I Learned - Rocky Kev

TIL how to pass unlimited arguments to a function

POSTED ON:

TAGS:

Functions normally

Let's say you have this situation:

const join = (string1, string2) => {
return string1 + string2
}

join("hi", " Rocky"); // "hi Rocky"

What if you want to have more strings?

For example, doing this will cause some issues.

join("Hello", " General", " Kenobi"); // "Hello General"

The solution:

This is known as the rest parameter syntax.

The rest parameter syntax allows a function to accept an indefinite number of arguments as an array, providing a way to represent variadic functions in JavaScript.

Via the MDN.

const join = (...strings) => {
  return strings.join('')
}

What's happening here?

  1. We destructure the arguments into an array. ...strings

  2. We then use the method join('') on our array to make the magic happen.

Real world use-cases:

We can also do some fancy things like this:

function sum(...theArgs) {
  return theArgs.reduce((previous, current) => {
    return previous + current;
  });
}

console.log(sum(1, 2, 3));
// expected output: 6

console.log(sum(1, 2, 3, 4));
// expected output: 10

And another example:

function myFun(a,  b, ...manyMoreArgs) {
  console.log("a", a)
  console.log("b", b)
  console.log("manyMoreArgs", manyMoreArgs)
}

myFun("one", "two", "three", "four", "five", "six")

// Console Output:
// a, one
// b, two
// manyMoreArgs, ["three", "four", "five", "six"]

via Flavio Scopes's How to accept unlimited parameters in a JavaScript function

MDN Documentation


Related TILs

Tagged:

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL How to steal localData using an XSS attack

But that's just a red flag that opens the door to bigger issues.

TIL Clear-Site-Data

The Clear-Site-Data header clears browsing data (cookies, storage, cache) associated with the requesting website. It allows web developers to have more control over the data stored by a client browser for their origins.