user1612293
user1612293

Reputation: 69

How does assignment to properties of the `arguments` object work?

Why does this function output 10?

function b (x, y, a) {
  arguments[2] = 10;
  console.log(a);
}

b(1, 2, 3);

Upvotes: 3

Views: 141

Answers (4)

Manish Nagar
Manish Nagar

Reputation: 1046

The arguments object is a local variable available within all functions; arguments as a property of Function can no longer be used

use this reference for further

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments

Upvotes: 2

NimChimpsky
NimChimpsky

Reputation: 47280

javascript arrays are zero indexed and arguments refers to parameters passed into function as arguments :

arguments[2] === a === 10

and

1 === x === arguments[0];
2 === y == arguments[1];

(and triple equality operator is not a mistake)

Upvotes: 9

Grant Thomas
Grant Thomas

Reputation: 45083

This function takes three inputs, discards the first two and displays the last in a modal popup, but not before assigning value 10 to index 2 of arguments - effectively setting the input a to 10 from 3 - it then exits scope without returning anything at all.

Upvotes: 1

BenM
BenM

Reputation: 53198

Because you're setting the third argument to 10. From MDN:

You can refer to a function's arguments within the function by using the arguments object. 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]

Upvotes: 4

Related Questions