Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript 'arguments' Keyword

Tags:

javascript

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]));
like image 629
Kevin Meredith Avatar asked Feb 10 '13 23:02

Kevin Meredith


People also ask

What is Arguments keyword in JavaScript?

arguments is an Array -like object accessible inside functions that contains the values of the arguments passed to that function.

What is Typeof arguments in JavaScript?

typeof is a JavaScript keyword that will return the type of a variable when you call it. You can use this to validate function parameters or check if variables are defined. There are other uses as well. The typeof operator is useful because it is an easy way to check the type of a variable in your code.

Does JavaScript have named arguments?

JavaScript, by default, does not support named parameters. However, you can do something similar using object literals and destructuring. You can avoid errors when calling the function without any arguments by assigning the object to the empty object, {} , even if you have default values set up.

What is this keyword in JavaScript?

In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object. Alone, this refers to the global object.


2 Answers

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.

like image 129
Pointy Avatar answered Sep 24 '22 16:09

Pointy


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.

like image 35
Niet the Dark Absol Avatar answered Sep 24 '22 16:09

Niet the Dark Absol