A Person
A Person

Reputation: 75

Javascript passing by reference instead of value in this case?

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.

Upvotes: 2

Views: 92

Answers (2)

felipezarco
felipezarco

Reputation: 86

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.

Upvotes: 3

Sahan Dissanayaka
Sahan Dissanayaka

Reputation: 621

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

So compiler confuse with the types

Upvotes: -1

Related Questions