I have always been under the impression that javascript was a Pass By Value language (where copies of all function parameters are used within functions rather than editing external variables by reference) so I was shocked to find out that running the code below changes the external variable 'one's value.
var one = [1];
var two = [2];
function broken(arr1, arr2) {
arr1[0] = arr2[0];
return arr1;
}
document.write("One: " + one + "<br>");
document.write("Two: " + two + "<br>");
document.write("Run 'broken': " + broken(one, two) + "<br>");
document.write("One: " + one + "<br>");
document.write("Two: " + two + "<br>");
Which produces this output:
> One: 1
> Two: 2
> Run 'broken': 2
> One: 2 //<------- this line
> Two: 2
As you can see, the value of the 'one' array has been changed by reference. What am I misunderstanding here? Thanks.