Search code examples
javascriptecmascript-6referencepass-by-referencevariable-assignment

Why does ES6 copy class variables inside methods?


I have a JavaScript/ES6 class with a member that is an array called x, initialized to [1,2,3,4].

When I declare a new variable in a method, called y, and assign x to it, and then change the values in x, y remains unchanged, indicating that y is a copy of x.

If I declare and assign y to a variable called z in the same method, modifying z changes y, but doesn't change x.

This would indicate that declaring a class level array (object?) and then assigning it to a variable inside a method copies the object. This differs significantly from languages like C#.

Why is it implemented this way in JavaScript/ES6?

class Alpha {
  constructor() {
    this.x = [1, 2, 3, 4];
  }

  DoSomething() {

    console.log('x is ' + this.x); // x is 1,2,3,4

    let y = this.x;
    this.x = [99, 99, 99, 99];

    console.log('x is ' + this.x); // x is 99,99,99,99
    console.log('y is ' + y); // y is 1,2,3,4 (?)

    let z = y;
    z[1] = 888;

    console.log('x is ' + this.x); // x is 99,99,99,99
    console.log('y is ' + y); // y is 1,888,3,4
    console.log('z is ' + z); // z is 1,888,3,4

  }
}

let thing = new Alpha();
thing.DoSomething()


Solution

  • let y = this.x;
    this.x = [99, 99, 99, 99];
    

    y now points to [1,2,3,4]....this.x now points to a new array [99,99,99,99];

    EDIT

    For the record, this has nothing to do with ES6

    EDIT #2

    y now points to a location in memory that contains the array [1,2,3,4] and this.x now points to a different location in memory that contains an array [99,99,99,99];

    At the heart of this question is the understanding of memory allocation.