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]);
}
}
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
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]);
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!
Pass any number of arguments to a function
This is fine;const myFunc = (...args: any) => {}
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]);
}
JavaScript: Pass unknown number of arguments from one method to another
You can use rest syntax to collect all the arguments into an array in acceptArguments
(which is preferred over using the arguments
variable), and then spread those arguments into the call of secondFunction
:
function acceptArguments(...args) {
secondFunction(...args);
}
function secondFunction(v1, v2, v3, v4) {
console.log(v1, v2, v3, v4);
}
acceptArguments(1, 2, 3, 4)
Related Topics
Resizing an Iframe Based on Content
Is There a "Null Coalescing" Operator in JavaScript
JavaScript Raises Syntaxerror With Data Rendered in Jinja Template
How to Get All Properties Values of a JavaScript Object (Without Knowing the Keys)
How to Loop Through a Plain JavaScript Object With the Objects as Members
Async Function Returning Promise, Instead of Value
"Uncaught Syntaxerror: Cannot Use Import Statement Outside a Module" When Importing Ecmascript 6
How to Enable Cors in Angularjs
Xml Parsing of a Variable String in JavaScript
Combination of Async Function + Await + Settimeout
Jquery .Live() VS .On() Method For Adding a Click Event After Loading Dynamic Html
Set a Default Parameter Value For a JavaScript Function
Canvascontext2D Drawimage() Issue [Onload and Cors]
Difference Between the '=' and '==' Operators and What Is '==='? (Single, Double, and Triple Equals)
Get Selected Text from a Drop-Down List (Select Box) Using Jquery
How to Access Post Form Fields in Express