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
arguments
is a special object that hooks into the Javascript internals of how local variables are stored.JS always copies the value for primitives
- fairly certain you're talking about passing by value. Passing by value means changes toa
inside the function have no relationship to anya
outside the function. It says nothing about howarguments
anda
are connected, which is probably by reference.