Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

javascript array passed by reference but

Why console.log(a) doesn’t return same result [1, 2, 3, 4] as console.log(b) ?

function test(c, d) {
  c = [1, 2, 3, 4];
  d.push(4);
}

a = [1, 2, 3];
b = [1, 2, 3];
test(a, b);
console.log(a);
console.log(b);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

With a = [1, 2, 3, 4]; you are overriding the argument (which is local to the function) you have passed into the function test. You are not making any changes to the actual array a.
Now the a inside does not even point to the array a outside.

But there is a change happening when you do b.push(4), which actually mutates the b array outside.

function test(a, b) {
  a = [1, 2, 3, 4];
  b.push(4);
}

a = [1, 2, 3];
b = [1, 2, 3];
test(a, b);
console.log(a);
console.log(b);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading