How can I convert the “arguments” object to an array in JavaScript?

ES6 using rest parameters

If you are able to use ES6 you can use:

Rest Parameters

function sortArgs(...args) {
  return args.sort(function (a, b) { return a - b; });
}

document.body.innerHTML = sortArgs(12, 4, 6, 8).toString();

As you can read in the link

The rest parameter syntax allows us to represent an indefinite number of arguments as an array.

If you are curious about the ... syntax, it is called Spread Operator and you can read more here.

ES6 using Array.from()

Using Array.from:

function sortArgs() {
  return Array.from(arguments).sort(function (a, b) { return a - b; });
}

document.body.innerHTML = sortArgs(12, 4, 6, 8).toString();

Array.from simply convert Array-like or Iterable objects into Array instances.



ES5

You can actually just use Array‘s slice function on an arguments object, and it will convert it into a standard JavaScript array. You’ll just have to reference it manually through Array’s prototype:

function sortArgs() {
    var args = Array.prototype.slice.call(arguments);
    return args.sort();
}

Why does this work? Well, here’s an excerpt from the ECMAScript 5 documentation itself:

NOTE: The slice function is intentionally generic; it does not require that its this value be an Array object. Therefore it can be transferred to other kinds of objects for use as a method. Whether the slice function can be applied successfully to a host object is implementation-dependent.

Therefore, slice works on anything that has a length property, which arguments conveniently does.


If Array.prototype.slice is too much of a mouthful for you, you can abbreviate it slightly by using array literals:

var args = [].slice.call(arguments);

However, I tend to feel that the former version is more explicit, so I’d prefer it instead. Abusing the array literal notation feels hacky and looks strange.

Leave a Comment