0

I am getting two different results for doing which I believe is the same thing in javascript with array push. Since I am new to javascript, I might be missing the big picture here.

Sample 1 -

class Test {

    constructor(){
        this.matrix = [];
    }

    createMatrix(){
        this.matrix.push([0,0,0]);
        this.matrix.push([0,0,0]);
        this.matrix.push([0,0,0]);
    }

    addNodes(x, y){
        this.matrix[x][y] = 1;
        this.matrix[y][x] = 1;
    }

    printMatrix(){
        return this.matrix;
    }
}

let test = new Test();
test.createMatrix();
console.log(test.printMatrix());
test.addNodes('1','2');
console.log(test.printMatrix());

O/p -

[ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ]

[ [ 0, 0, 0 ], [ 0, 0, 1 ], [ 0, 1, 0 ] ]

Sample 2 -

Replacing the createMatrix method with below one, gives me another result when trying to addNodes.

createMatrix(){
        let row = [0,0,0];
        this.matrix.push(row);
        this.matrix.push(row);
        this.matrix.push(row);
    }

O/p -

[ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ]

[ [ 0, 1, 1 ], [ 0, 1, 1 ], [ 0, 1, 1 ] ]

Please help me understand what I am missing out here, I want to achieve is o/p of sample 1 with the sample 2 code.

  • 2
    You're creating 3 different array objects, vs. just one array object which you're pushing three times…! – deceze Nov 11 '21 at 13:33
  • I am thinking about the output, why am I getting different result when using addNodes. – Vijay Bhatt Nov 11 '21 at 13:38
  • There's only *one object in memory* in the second case. This is an important point to visualise. One. Array. Object. In. Memory. If you modify that, everyone that has a reference to that one object will see it being modified. – deceze Nov 11 '21 at 13:45
  • thanks got it. Need different objects then, for the expected output. – Vijay Bhatt Nov 11 '21 at 13:52

1 Answers1

0

it is a matter of reference. In the second example, you are inputting the same array 3 times with the push function. The 3 arrays are pointing to the same memory address, which is referenced by the variable rows.

In the first example there are 3 different arrays, with 3 different memory addresses

Henrique Viana
  • 645
  • 4
  • 12
  • thanks this helped me to understand it better. Got it every time I need to create a new row object if I want the expected output. – Vijay Bhatt Nov 11 '21 at 13:50