Reputation: 157
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]);
Upvotes: 1
Views: 1402
Reputation: 318182
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.
Upvotes: 3
Reputation: 9746
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();
Upvotes: 0
Reputation: 11
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);
Upvotes: 1