Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
Javascript: Push function behave differently with array with reference and without reference

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!