1

What is the difference between using arguments and Array.prototype.slice.call(arguments,0) in a function? I don't see there is any much difference between both, so How would I know when I am supposed to use which one?

function arr(){
  return arguments; // or return Array.prototype.slice.call(arguments,0);
}
arr([1,2,3],[4,5,6]);
Someone
  • 157
  • 2
  • 3
  • 10
  • possible duplicate of [How can I convert the "arguments" object to an array in JavaScript?](http://stackoverflow.com/questions/960866/how-can-i-convert-the-arguments-object-to-an-array-in-javascript). The first paragraph explain several disadvantages of the `arguments`object and why a programmer would convert it to an actual `Array`. – Paul Jul 25 '15 at 23:21

3 Answers3

3

The difference is that arguments is an "array-like" object, not an array.

You can convert the arguments object to a real array by slicing it, like so

Array.prototype.slice.call(arguments, 0);

This gives you an array, with array properties like forEach, pop etc. which objects like arguments don't have (except length, which arguments do have).

It is generally (almost) never a good idea to slice the arguments object, MDN gives the warning

You should not slice on arguments because it prevents optimizations in JavaScript engines (V8 for example). Instead, try constructing a new array by iterating through the arguments object.

Also there should be no real need to pass arguments to a function, only to return them.

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • To be specific, it's an array-like object. Which is generally what people call non-arrays that are indexed by numbers and have a `.length` property. There are many such things in js. The `HTMLCollection` returned by `document.getElementsByClassName()` is another example – slebetman Jul 25 '15 at 23:36
  • @slebetman - It's really just an obect with a `length` property, often called "array-like". – adeneo Jul 25 '15 at 23:43
1

The arguments object is not a real array. It is a special type of object and does not have any Array properties except "length".

To make an array from the arguments object, use Array.prototype.slice.call(arguments, 0);

0

arguments variable is special kind of Object, and is not Array. So, you can't use .forEach, .map, '.push' and other array functions with it.

You have to convert arguments to Array and then you can work with value as array

function test(){
  console.log(arguments.forEach); // undefined
  var argsArray = Array.prototype.slice.call(arguments,0);
  console.log(argsArray.forEach); // function
}
test();
just-boris
  • 9,468
  • 5
  • 48
  • 84