12

Consider:

> function hello(what) {
.     what = "world";
.     return "Hello, " + arguments[0] + "!";
. }
> hello("shazow")
"Hello, world!"

Why does changing the value of what change the value of arguments[0]?

David Wolever
  • 148,955
  • 89
  • 346
  • 502

1 Answers1

13

"Why does changing the value of what change the value of arguments[0]?"

Because that's how it's designed to work. The formal parameters are directly mapped to the indices of the arguments object.

That is unless you're in strict mode, and your environment supports it. Then updating one doesn't effect the other.

function hello(what) {
    "use strict"; // <-- run the code in strict mode
    what = "world";
    return "Hello, " + arguments[0] + "!";
}
hello("shazow"); // "Hello, shazow!"
  • Oh… In that case: why is it designed to work that way? And is that design documented anywhere? (not that I don't trust you, of course, I'd just like a bit more detail) – David Wolever Apr 19 '12 at 02:54
  • Oh, wait, here we go: "NOTE 1" in *10.6 Arguments Object* of http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf – David Wolever Apr 19 '12 at 02:56
  • @DavidWolever: The language is document in the ECMAScript specification. Strict mode was introduced in ECMAScript 5. –  Apr 19 '12 at 02:56
  • @DavidWolever—for convenience, there is an [HTML version of ES5](http://es5.github.com/) on github. – RobG Apr 19 '12 at 02:59
  • A little lighter reading than the official spec: https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope/arguments – jfriend00 Apr 19 '12 at 03:00
  • @RobG oh, that is significantly more convenient. Thanks. – David Wolever Apr 19 '12 at 03:07
  • @jfriend00 I might simply be blind… But I don't see any reference to this behaviour in that document =\ – David Wolever Apr 19 '12 at 03:08
  • Look in [§10.5 Declaration Binding Instantiation](http://es5.github.com/#x10.5) step 7 b and c, note that in non-strict mode, *SetMutableBinding* concrete method is set using `false`. The specs are written in a way that if you don't know the answer, it can be very difficult to find things. – RobG Apr 19 '12 at 03:20