Equating arrays in JavaScript

Equating arrays in JavaScript

chboccachbocca Posts: 63Questions: 11Answers: 0
edited August 18 in General

This post is just general JavaScript observation.

I was surprised by this result!

const a = [1, 2, 3, 4];
const b = a;

console.log("before push ... a: " + a);
console.log("before push ... b: " + b);


console.log("after push a: " + a);
console.log("after push b: " + b);

before push ... a: 1,2,3,4
before push ... b: 1,2,3,4

after push ... a: 1,2,3,4,5
after push ... b: 1,2,3,4,5

Simple demo.

Still learning object oriented code, I guess.


  • kthorngrenkthorngren Posts: 16,808Questions: 25Answers: 3,983

    That is expected behavior. For particular types of objects using const b = a; is copying the object reference not the object itself. So both a and b reference the same object in memory. This page will probably do a better job of explaining.


  • allanallan Posts: 56,849Questions: 1Answers: 9,035 Site admin

    Also, you can use .slice() on an array to create a shallow copy of it.

    This is the kind of thing where I'm glad I learned C first with its pointers!


  • chboccachbocca Posts: 63Questions: 11Answers: 0

    Good stuff. Thank you Kevin and Allan.

Sign In or Register to comment.