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]);

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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 - It's really just an obect with a length property, often called "array-like".
That warning is no longer on the page.
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);

Comments

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();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.