Equating arrays in JavaScript

Equating arrays in JavaScript

chboccachbocca Posts: 86Questions: 13Answers: 1
edited August 2022 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);

a.push(5);

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.

Replies

  • kthorngrenkthorngren Posts: 20,145Questions: 26Answers: 4,736

    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.
    https://javascript.info/object-copy

    Kevin

  • allanallan Posts: 61,449Questions: 1Answers: 10,055 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!

    Allan

  • chboccachbocca Posts: 86Questions: 13Answers: 1

    Good stuff. Thank you Kevin and Allan.

Sign In or Register to comment.