Like A Girl

Pushing the conversation on gender equality.

Code Like A Girl

Javascript: creating true copies of arrays

If you need to create an independent copy of an array, you must use slice() at the end.

let originalArray = [1,2,3];
let copiedArray = originalArray.slice();
copiedArray.push(4); 
console.log(copiedArray);   // [1,2,3,4]
console.log(originalArray); // [1,2,3]

If you do not use slice(), you will end up with all the arrays pointing to the same value. Whenever you change either array, you will change the underlying value and all the array values will continue to equal each other.

let originalArray = [1,2,3];
let copiedArray = originalArray; // DANGER! Not using splice()
copiedArray.push(4);
console.log(copiedArray);    // [1,2,3,4]
console.log(originalArray); // [1,2,3,4]
originalArray.push(7);
console.log(copiedArray);   // [1,2,3,4,7]
console.log(originalArray); // [1,2,3,4,7]

I’m sure there’s proper coding terms for all of this, like references and shallow copies or something. But I don’t know what they are yet!