Equating arrays in JavaScript
Equating arrays in JavaScript
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
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
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
Good stuff. Thank you Kevin and Allan.