Recently I started learning JavaScript through Nicholas C. Zakas' book Professional JavaScript For Web Developers and I came across some questions that I could not solve by myself.
As the title says, that's all about named arguments and arguments object in JavaScript functions.
E.g. we have this piece of code:
function doAdd(num1 , num2) {
arguments[1] = 10;
alert(arguments[0] + num2);
}
doAdd(10 , 20);
The book says that values in the arguments object are automatically reflected by the corresponding named arguments, so num2
enters the function with a value of 20 and then it gets overwritten via arguments[1]
and finally gets a value of 10.All good all clear up to this point. Then it says that
this effect goes only one way: changing the named argument does not result in a change to the corresponding value in arguments.
And that's where the problems start.
I tried to modify this code a bit to understand what the author says but I failed.
E.g.
function doAdd(num1 , num2) {
arguments[1] = 10;
num2 = 40;
alert(arguments[0] + arguments[1]);
}
doAdd(10 , 20);
This time num2
enters function with a value of 20 again, it changes to 10 via arguments[1]
and then it changes once more to 40 via the named argument num2
this time. Alert pops up 50, since a change to a named argument does not result in a change to the corresponding value in arguments
. Why does alert not pop up 20?