1

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

2 Answers 2

2

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})
}
Sign up to request clarification or add additional context in comments.

1 Comment

How does using the call method on the slice function turn the arguments object into an array?
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.