TIL how to pass unlimited arguments to a function
POSTED ON:
TAGS: mdn functions javascript
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?
-
We destructure the arguments into an array.
...strings
-
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
Related TILs
Tagged: mdn