3

Why does this function alert 10?

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

b(1, 2, 3);
Paul
  • 26,170
  • 12
  • 85
  • 119
user1612293
  • 69
  • 1
  • 8
  • 3
    It isn't *returning* anything. – BenM Dec 31 '12 at 10:57
  • I don't do much javascript, but a Google for "javascript arguments" gave me a good result as the very first result – PeterJ Dec 31 '12 at 10:58
  • I thought that arguments is just another array :( – user1612293 Dec 31 '12 at 11:02
  • @user1612293 Well I didn't know either for a start, just saying it was a pretty easy Google search, so I've learnt something new too :-) – PeterJ Dec 31 '12 at 11:05
  • `arguments` is an object, that resembles an array, but it isn't an array (it has a `length` property, but doesn't have the `slice` method, for example... it also has the `callee` property - which you musn't use) – Elias Van Ootegem Dec 31 '12 at 11:09

4 Answers4

9

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)

Community
  • 1
  • 1
NimChimpsky
  • 46,453
  • 60
  • 198
  • 311
  • Perhaps worth mentioning: it's not a very good idea to change the `arguments` object directly. Perhaps use `var writeableArgs = Array.prototype.slice(arguments,[0]);`, and use the returned array instead – Elias Van Ootegem Dec 31 '12 at 11:07
4

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]
BenM
  • 52,573
  • 26
  • 113
  • 168
3

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

Manish Nagar
  • 1,038
  • 7
  • 12
1

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.

Grant Thomas
  • 44,454
  • 10
  • 85
  • 129