mike
mike

Reputation: 43

Using the arguments object in functions

Why does the foo function work fine.

function foo (a,b) {
  return arguments.length;
}

But, the boo function returns undefined is not a function, even though I pass arguments in the function.

function boo (a,b) {
  return arguments.slice(0);
}

Upvotes: 1

Views: 37

Answers (2)

BatScream
BatScream

Reputation: 19700

arguments is an object and not an array. If you print it and see, you can see an object:

function foo (a,b) {
    console.log(arguments);
}

foo(10,20);

o/p: { '0': 10, '1': 20 }

From the docs,

This object contains an entry for each argument passed to the function, the first entry's index starting at 0. For example, if a function is passed three arguments, you can refer to the argument as follows:

 arguments[0] arguments[1] arguments[2]

It does not have any Array properties except length.

So, return arguments.slice(0); would fail, since slice belongs to the prototype of an array.

Upvotes: 0

elclanrs
elclanrs

Reputation: 94101

arguments is not an array, but an array-like object. Many array methods work on array-like objects, because they expect an object with numeric properties, and a length property, such as arguments. You can use the built-in functions by using call and passing the object as the this value:

var args = Array.prototype.slice.call(arguments);
//^ args is a real array now

This works with other methods as well, like reduce:

function sum(/*...args*/) {
  return [].reduce.call(arguments, function(x, y){return x + y})
}

Upvotes: 2

Related Questions