Is it possible to send a variable number of arguments to a JavaScript function?
Update: Since ES6, you can simply use the spread syntax when calling the function:
func(...arr);
Since ES6 also if you expect to treat your arguments as an array, you can also use the spread syntax in the parameter list, for example:
function func(...args) {
args.forEach(arg => console.log(arg))
}
const values = ['a', 'b', 'c']
func(...values)
func(1, 2, 3)
And you can combine it with normal parameters, for example if you want to receive the first two arguments separately and the rest as an array:
function func(first, second, ...theRest) {
//...
}
And maybe is useful to you, that you can know how many arguments a function expects:
var test = function (one, two, three) {};
test.length == 3;
But anyway you can pass an arbitrary number of arguments...
The spread syntax is shorter and "sweeter" than apply
and if you don't need to set the this
value in the function call, this is the way to go.
Here is an apply example, which was the former way to do it:
var arr = ['a','b','c'];
function func() {
console.log(this); // 'test'
console.log(arguments.length); // 3
for(var i = 0; i < arguments.length; i++) {
console.log(arguments[i]);
}
};
func.apply('test', arr);
Nowadays I only recommend using apply
only if you need to pass an arbitrary number of arguments from an array and set the this
value. apply
takes is the this
value as the first arguments, which will be used on the function invocation, if we use null
in non-strict code, the this
keyword will refer to the Global object (window) inside func
, in strict mode, when explicitly using 'use strict' or in ES modules, null
will be used.
Also note that the arguments
object is not really an Array, you can convert it by:
var argsArray = Array.prototype.slice.call(arguments);
And in ES6:
const argsArray = [...arguments] // or Array.from(arguments)
But you rarely use the arguments
object directly nowadays thanks to the spread syntax.
Passing Variable Number of arguments in javascript function argument-list
You can pass multiple parameters in your function and access them via arguments variable. Here is an example of function which returns the sum of all parameters you passed in it
var sum = function () {
var res = 0;
for (var i = 0; i < arguments.length; i++) {
res += parseInt(arguments[i]);
}
return res;
}
You can call it as follows:
sum(1, 2, 3); // returns 6
Pass in any number of arguments into a Javascript function
You actually don't need to define any arguments in the function parameters. All you need to do is access javascript's built in arguments
object.
So your code could look like the following:
function test() {
var a = arguments[0];
var b = arguments[1];
var c = arguments[2];
console.log(a);
console.log(b);
console.log(c);
}
test("a", "b", "c");
For reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
JavaScript variable number of arguments to function
Sure, just use the arguments
object.
function foo() {
for (var i = 0; i < arguments.length; i++) {
console.log(arguments[i]);
}
}
Passing variable number of arguments from one function to another
The main way to pass a programmatically generated set of arguments to a function is by using the function's 'apply' method.
function show(foo, bar) {
window.alert(foo+' '+bar);
}
function run(f) {
// use splice to get all the arguments after 'f'
var args = Array.prototype.splice.call(arguments, 1);
f.apply(null, args);
}
run(show, 'foo', 'bar');
Call a function with a variable number of arguments in JavaScript (similar to call())
It turns out that Felix King had the right idea/was the closest. I found a direct answer to my question as soon as I realized what I was actually trying to do, which is pass forward arguments from function to function (found the answer here). So I got this to work with this code:
function recursiveSetFncApply(set, fnc/*, variable */) {
var me = this;
var parentArgs = arguments;
set.forEach(function(element) {
if (element.type == 'set') {
parentArgs[0] = element;
me._recursiveSetFncApply.apply(me, parentArgs);
} else {
// Generate args from optional arguments and pass forward; put element in args at front
var args = Array.prototype.slice.call(parentArgs, 2);
args.unshift(element);
fnc.apply(element, args);
}
});
}
I make a reference to arguments
with parentArgs
because I need to update the set
property in arguments
before I pass it forward to the next recursive loop, otherwise I hit an infinite loop because it hasn't updated at all because it's using the original arguments set. I was under the impression that apply()
will not actually pass forward arguments, but simply pop an array into the new function that you have to access by index--this isn't the case. When I used apply()
on translateElementOperation
, I had all the arguments I needed in their exact places. Here's the updated function I ran through the recursive apply:
function translateElementOperation(element, operation, x, y) {
var currentPath = element.attr('path');
translatedPath = Raphael.transformPath(currentPath, [operation, x, y]);
element.attr('path', translatedPath);
}
Thanks for the help, everyone!
how to create functions with variable arguments in javascript?
You can access the arguments by their ordinal position without the need to state them in the prototype as follows:
function myFunction() {
for (var i = 0; i < arguments.length; i++)
alert(arguments[i]);
}
myFunction(1, 2, "three");
>>1
>>2
>>three
Or if you really are passing in a set of semantically related numbers you could use an array;
function myFunction(arr) { ... }
result = myFunction([1,2,3]);
Pass unknown number of arguments into JavaScript function
ES3 (or ES5 or oldschool JavaScript)
You can access the arguments passed to any JavaScript function via the magic arguments
object, which behaves similarly to an array. Using arguments
your function would look like:
var print_names = function() {
for (var i=0; i<arguments.length; i++) console.log(arguments[i]);
}
It's important to note that arguments
is not an array. MDC has some good documentation on it: https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#Using_the_arguments_object
If you want to turn arguments
into an array so that you can do things like .slice()
, .push()
etc, use something like this:
var args = Array.prototype.slice.call(arguments);
ES6 / Typescript
There's a better way! The new rest parameters feature has your back:
var print_names = function(...names) {
for (let i=0; i<names.length; i++) console.log(names[i]);
}
Calling function with a varying number of arguments (JS)
You need the spread operator. It destructures your array and passes the items as separate variables.
var array = [1, 2, 3, 4, 5]; console.log("test", ...array); // ES6 and higherconsole.log.apply(console, ["test"].concat(array)); // ES5
Related Topics
Webdriver Click() VS JavaScript Click()
How to Cancel an Http Fetch() Request
Open a New Tab in the Background
Is There a Null-Coalescing (Elvis) Operator or Safe Navigation Operator in JavaScript
Over_Query_Limit in Google Maps API V3: How to Pause/Delay in JavaScript to Slow It Down
I Know That Callback Function Runs Asynchronously, But Why
Detecting When User Scrolls to Bottom of Div with Jquery
Parse Error: Adjacent Jsx Elements Must Be Wrapped in an Enclosing Tag
Prevent Scrolling of Parent Element When Inner Element Scroll Position Reaches Top/Bottom
How to Access Svg Elements with JavaScript
How to Bind Fancybox to Dynamic Added Element
Using Jquery's Ajax Method to Retrieve Images as a Blob
Maximum Size of an Array in JavaScript
Is There Any Non-Eval Way to Create a Function with a Runtime-Determined Name
Function with Foreach Returns Undefined Even with Return Statement