As shown in the JS snippet below, arguments[0]
and a
always keep the same value. This is well-known in JS, but I'm still curious how this is implemented.
For example, if both a
and arguments[0]
are referencing to the same JS object, it's understandable that they always get the updated value. But this cannot explain the situation for primitive values like 1.
If I understand correctly, JS always copies the value for primitives which implies that both a
and object[0]
hold a copy of this value. If this is the case, how are a
and arguments[0]
always synced?
function func(a, b) {
console.log("a = " + a);
console.log("arguments[0] = " + arguments[0]);
arguments[0] = 123;
console.log("a = " + a);
console.log("arguments[0] = " + arguments[0]);
a = 123456;
console.log("a = " + a);
console.log("arguments[0] = " + arguments[0]);
}
func(1, 2);
Here is the output:
>node test.js
a = 1
arguments[0] = 1
a = 123
arguments[0] = 123
a = 123456
arguments[0] = 123456
The arguments
object is special, it hooks into the way the Javascript implementation stores the function arguments. So when you assign to arguments[n]
, it actually finds the memory block used to hold the parameter variables, and puts the value you're assigning there. And that same memory location is also used when referencing the parameter variables by name.
Another way to think about it is that every function has a local arguments
array-like object. When the JS implementation compiles the function definition, it replaces all the parameter variables with references to that array. So expressions that use a
are compiled as if they'd used arguments[0]
, b
is translated to arguments[1]
, and so on.