2

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.

zmag
  • 7,825
  • 12
  • 32
  • 42
A Person
  • 75
  • 7
  • 2
    JS uses [call-by-sharing](https://medium.com/wwstay-engineering/javascript-call-by-sharing-2d3ca42c4d02) – zzzzBov Feb 12 '20 at 02:42
  • There's an explanation about **Passing by value of references** in the same page. https://www.javascripttutorial.net/javascript-pass-by-value/ – zmag Feb 12 '20 at 02:50
  • Does this answer your question? [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – zmag Feb 12 '20 at 02:51
  • you did not misunderstand, just you passed by reference, so whenever you changed so it is reflecting the change globally of that array – Mahamudul Hasan Feb 12 '20 at 02:51

2 Answers2

3

The behavior of the broken function is correct.

Just like with object properties, if you modify a value of an array (but not the array itself), it will modify the original.

Let's say we have an array

letters = ['A','C']

function willNotModify(array) { 
  array = ['A','Z']
}

function willModify(array) {
  array[1] = 'B'
}

willNotModify(letters) // letters array is unchanged 
willModify(letters)    // letters array is now ["A", "B"]

Hope this clarify your understanding.

zOnNet
  • 86
  • 5
-1

in the broken function your parameters are array references and you pass two variable values

So compiler confuse with the types

Sahan Dissanayaka
  • 591
  • 2
  • 8
  • 26