8

My understanding is that I can call Array.prototype.slice.call(arguments, 1) to return the tail of an array.

Why won't this code return [2,3,4,5]?

function foo() {  
    return Array.prototype.slice.call(arguments,1);
}

alert(foo([1,2,3,4,5]));

3 Answers 3

13

Because you're only passing one argument — the array.

Try alert(foo(1,2,3,4,5));

Arguments are numbered from 0 in JavaScript, so when you start your slice at 1 and pass 1 argument, you get nothing.

Note that it can hamper optimization to allow the arguments object to "leak" out of a function. Because of the aliasing between arguments and the formal parameters, an optimizer can't really do any static analysis of the function if the arguments object gets sent somewhere else, because it has no idea what might happen to the parameter variables.

2
  • Would it be better, then, to copy the arguments? function foo() { var args = arguments; return Array.prototype.slice.call(args,1); }
    – Eric
    Commented May 16, 2016 at 17:45
  • 1
    The MDN article on the arguments keyword describes this optimization problem you mentioned: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    – Eric
    Commented May 16, 2016 at 17:50
13

arguments is an array-like object that lists the arguments and a few other properties (such as a reference to the current function in arguments.callee).

In this case, your arguments object looks like this:

arguments {
    0: [1,2,3,4,5],
    length: 1,
    other properties here
}

I think this explains the behaviour you're seeing quite well. Try removing the array brackets in the function call, or use arguments[0] to access the arry.

3

Because arguments is {0: [1,2,3,4,5], length: 1}, which is an array-like object with one element. The tail of an array with one element is the empty array.

Either change the definition of the function:

function foo(arr) {  
    return Array.prototype.slice.call(arr,1);
}

or call the function with:

foo(1,2,3,4,5);

Not the answer you're looking for? Browse other questions tagged or ask your own question.