55

Can a JavaScript function take unlimited arguments? Something like this:

testArray(1, 2, 3, 4, 5...);

I am trying:

var arr = [];
function testArray(A) {
    arr.push(A);
}

But this doesn't work (output is only the first argument). Or the only way is:

function testArray(a, b, c, d, e...) {

}

Thanks

Timo Tijhof
  • 10,032
  • 6
  • 34
  • 48
rhavd
  • 773
  • 2
  • 8
  • 9
  • As an alternative, you could have one parameter - "unlimited" container such as array (or object) and then just pass everything as array, even if there is only `...([one_arg])`... – jave.web May 31 '16 at 11:14
  • Note that to directly answer the question, [No you can't.](http://stackoverflow.com/questions/22747068/is-there-a-max-number-of-arguments-javascript-functions-can-accept) – Kaiido May 17 '17 at 04:19

9 Answers9

71

There's a weird "magic" variable you can reference called "arguments":

function manyArgs() {
  for (var i = 0; i < arguments.length; ++i)
    alert(arguments[i]);
}

It's like an array, but it's not an array. In fact it's so weird that you really shouldn't use it much at all. A common practice is to get the values of it into a real array:

function foo() {
  var args = Array.prototype.slice.call(arguments, 0);
  // ...

In that example, "args" would be a normal array, without any of the weirdness. There are all sorts of nasty problems with "arguments", and in ECMAScript 5 its functionality will be curtailed.

edit — though using the .slice() function sure is convenient, it turns out that passing the arguments object out of a function causes headaches for optimization, so much so that functions that do it may not get optimized at all. The simple, straightforward way to turn arguments into an array is therefore

function foo() {
  var args = [];
  for (var i = 0; i < arguments.length; ++i) args[i] = arguments[i];
  // ...
}

More about arguments and optimization.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 3
    There is nothing "magic" or weird about it, the arguments object is defined in ECMA-262. The only similarity it has with an array is that it's length property is one more than its highest numeric property name. Other than that, it's just an object with properties. – RobG Jun 18 '11 at 14:06
  • 7
    I was being poetic :-) And the "arguments" variable *is* weird - it's also got things like the "callee" property. – Pointy Jun 18 '11 at 14:06
  • @SmartLemon I'm not sure I know exactly what you mean. I was not trying to be unhelpful. Americans have no understanding of that expression beyond "extracting urine from it". – Pointy Mar 20 '13 at 03:03
  • 1
    Sorry xD. I guess its not the common expression around there. Its like making fun of it. In this case it is like you are making fun of the question as if we should know it anyway. – FabianCook Mar 20 '13 at 03:19
  • @SmartLemon ah I see :-) Well I wasn't really making fun of the question; the `arguments` object really is strange, and the designer of the language himself considers it to be a mistake now. – Pointy Mar 20 '13 at 14:49
  • 2
    Here in this its explained in detail http://stackoverflow.com/questions/5145032/whats-the-use-of-array-prototype-slice-callarray-0 – PHP Avenger May 14 '13 at 21:39
33

As of ECMAScript 2015 (or ES6) we also have access to rest parameters that give us a slightly cleaner way to manage arguments:

function foo(a, b, ...others) {
    console.log("a and b are ", a, b);

    for (let val of others) {
        console.log(val);
    }
}

foo(1, 2, 3, 4, 5);

At the time of this writing, this is supported by Chrome 47+, Firefox 15+, and Edge. The feature is also available via both Babel and TypeScript transpiling down to ES5.

  • 1
    Thank you, this is exactly what I was looking for. Especially the MDN link, I just couldnt remember the name of it. :) – Noitidart Mar 16 '16 at 04:43
9

With ECMAScript 6, you can use rest of arguments syntax:

const testArray = (...args) => {
    console.log(args);
};

testArray(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Marius Tancredi
  • 1,181
  • 1
  • 10
  • 9
3

There are some legacy methods but I prefer the ES6 and newer versions, So if I wanna implement this, I wrote it like below:

const func = (...arg) => console.log(arg);

Simple and cutting edge of tech.

AmerllicA
  • 29,059
  • 15
  • 130
  • 154
3

Javascript ES5

function testArray(){
    for(index = 0; index < arguments.length; i++) {
        alert(arguments[index])
    }
}

Javascript ES6

const testArray = (...arg) => console.log(arg)
Pengguna
  • 4,636
  • 1
  • 27
  • 32
1

You can also just "cast" it, saving you the ugly loop:

var getArguments = function() {
    return arguments;
};

var foo = getArguments(1,2,3,4);

// console.log(foo.slice()); => TypeError: foo.slice is not a function

var foo = Object.values(foo); 

console.log(foo); // => [ 1, 2, 3, 4 ]

foo.push(5);

console.log(foo); // => [ 1, 2, 3, 4, 5 ]
1
function toArray() {
   return arguments;
}

var myargs = toArray(1, 2, 3, 4, 5, 6);

The arguments keyword is available in every js function

Timo Tijhof
  • 10,032
  • 6
  • 34
  • 48
Zoidberg
  • 10,137
  • 2
  • 31
  • 53
1
var arr = [];
function testArray() {
    Array.prototype.push.apply(arr, arguments);
}
clyfish
  • 10,240
  • 2
  • 31
  • 23
0

const outputDiv=document.querySelector('.output');
const output=(...x)=>{
    return outputDiv.innerHTML=x;
}

output(1,2,3,4,['hello',5,6],true,null);
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Javascript Practice</title>
    <link href="https://fonts.googleapis.com/css2?family=Raleway:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,800;1,900&display=swap" rel="stylesheet">


    <style>
        body{font-family: 'Raleway', sans-serif; background-color: #060606;}
        .center{height:100vh; width: 100%; display: grid;align-items:center;justify-content: center;}
        .output{font-size: 15px;color: rgb(59, 59, 255);font-weight: 200;}
    </style>
    
</head>
<body>
    <div class="center">
        <div class='output'></div>
    </div>

    <script src="js.js"></script>
</body>
</html>
  • 3
    Please explain why/how this solves the problem, see [How To Answer](https://stackoverflow.com/help/how-to-answer) – jasie Sep 29 '20 at 07:17