Unlimited arguments in a JavaScript function

Viewed 36271

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

9 Answers

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.

Javascript ES5

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

Javascript ES6

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

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>

Related