59

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

2
  • 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])... Commented May 31, 2016 at 11:14
  • Note that to directly answer the question, No you can't. Commented May 17, 2017 at 4:19

9 Answers 9

72

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.

Sign up to request clarification or add additional context in comments.

6 Comments

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.
I was being poetic :-) And the "arguments" variable is weird - it's also got things like the "callee" property.
@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".
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.
Here in this its explained in detail stackoverflow.com/questions/5145032/…
|
36

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 Comment

Thank you, this is exactly what I was looking for. Especially the MDN link, I just couldnt remember the name of it. :)
10

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);

Comments

3

Javascript ES5

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

Javascript ES6

const testArray = (...arg) => console.log(arg)

Comments

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.

2 Comments

This is not quite valid JavaScript. I recommend the other answers to this question for an explanation of this feature.
@LucienGreathouse, thanks for your comment, I added parenthesis, it works now, sorry for my bad.
1
var arr = [];
function testArray() {
    Array.prototype.push.apply(arr, arguments);
}

Comments

1
function toArray() {
   return arguments;
}

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

The arguments keyword is available in every js function

1 Comment

arguments is not of "type" Array, its just a sort of "iterable", and that is pretty lame on JS side.
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 ]

Comments

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>

1 Comment

Please explain why/how this solves the problem, see How To Answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.