Can You Spot The Bug?
Here’s a sample of the code in question, that you can run from NodeJS. I’m using NodeJS 0.10.26 in this case.
There isn’t anything terribly special here. Check the number of arguments. If it’s 2, then re-assign the ‘a’ variable to a default, reassign ‘b’ to what ‘a’ originally was, and reassign ‘c’ to what ‘b’ originally was. Note that I’m doing this reassignment through the use of the arguments array, as well.
Can you guess what the output is, based on the code above?
Why are my parameters empty?
How I Thought Parameters Worked
I’ve always assumed method parameters worked the same way as variables. If I have 2 variables pointing at the same data, and I reassign one of them, then the other one is not reassigned.
Given this by-val nature of the named parameter -> arguments[n] relationship, when my code above assigned “a” to an empty string it wiped out the “arguments” value as well.
Fixing The Bug: Reverse The Reassignment Order
In order to work around this, you have to reassign the parameters in reverse order.
And now the results are what I expected: