shmuli
shmuli

Reputation: 5192

The "unusual" feature of the Arguments object

This is a quote from the Core JavaScript Reference in "JavaScript, the Definitive Guide" regarding the arguments object:

In non-strict mode, the Arguments object has one very unusual feature. When a function has named arguments, the array elements of the Arguments object are synonyms for the local variables that hold the function arguments. The Arguments object and the argument names provide two different ways of referring to the same variable. Changing the value of an argument with an argument name changes the value that is retrieved through the Arguments object, and changing the value of an argument through the Arguments object changes the value that is retrieved by the argument name.

In simple terms, what does this mean? An example would be great.

Upvotes: 1

Views: 51

Answers (1)

Pointy
Pointy

Reputation: 413737

Try this:

function x(a, b) {
  arguments[1] = "foo";
  console.log(b);
}

x("hello", "world");

You'll see "foo" in the console. The arguments object has array-like properties that alias the formal parameters declared by the function. That means that when you change arguments[0], that also changes the value of the first explicitly-declared formal parameter. There's no other way in JavaScript to alias variables, so that makes arguments "unusual".

Upvotes: 1

Related Questions