JavaScript variable number of arguments to function

Timo picture Timo · Jan 26, 2010 · Viewed 353.6k times · Source

Is there a way to allow "unlimited" vars for a function in JavaScript?

Example:

load(var1, var2, var3, var4, var5, etc...)
load(var1)

Answer

roufamatic picture roufamatic · Jan 26, 2010

Sure, just use the arguments object.

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