Passing an arbitrary number of arguments to a JavaScript function

In C# you can specify that an arbitrary number of arguments / parameters can be passed to a function using the params keyword. This looks something like this:

bool areAllChecked(params CheckBox[] checkBoxes) {
  foreach (CheckBox checkBox in checkBoxes) {
    if (!checkBox.Checked) return false;
  }
  return true;
}
...
bool areAllChecked = areAllChecked(checkBox1, checkBox2, ..., checkBoxN);

Unsurprisingly (being a dynamic language and all), you can do this in JavaScript as well using the arguments object:

function areAllChecked() {
  for (var i=0; i<arguments.length; i++) {
    if (!arguments[i].checked) return false;
  }
  return true;
}
var areAllChecked = areAllChecked(checkBox1, checkBox2, ..., checkBoxN);

Comments