Sometimes, we want to pass all the values from an array into a function as arguments with JavaScript.
In this article, we’ll look at how to pass all the values from an array into a function as arguments with JavaScript.
How to pass all the values from an array into a function as arguments with JavaScript?
To pass all the values from an array into a function as arguments with JavaScript, we can use the spread and rest operators.
For instance, we write:
const f = (...args) => {
console.log(args)
}
const a = ['a', 'b', 'c', 'd']
f(...a)
to define the function f
that uses the rest operator in the arguments to accept an unlimited number of arguments.
args
is an array with all the arguments.
Then we call f
with array a
‘s entries spread as the arguments of f
with the spread operator.
Therefore, args
is ["a", "b", "c", "d"]
.
Conclusion
To pass all the values from an array into a function as arguments with JavaScript, we can use the spread and rest operators.