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]));
Bergi
671k162 gold badges1k silver badges1.5k bronze badges
asked Feb 10, 2013 at 23:37

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.

answered Feb 10, 2013 at 23:38
Sign up to request clarification or add additional context in comments.

2 Comments

Would it be better, then, to copy the arguments? function foo() { var args = arguments; return Array.prototype.slice.call(args,1); }
The MDN article on the arguments keyword describes this optimization problem you mentioned: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
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.

answered Feb 10, 2013 at 23:41

Comments

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);
answered Feb 10, 2013 at 23:40

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.