Array references vs shallow copies

Jeff P
1 min readNov 13, 2023

--

consider the following:

const bookList = [
"The Hound of the Baskervilles",
"On The Electrodynamics of Moving Bodies",
"Philosophiæ Naturalis Principia Mathematica",
"Disquisitiones Arithmeticae"
];


const newBookList = bookList;

It might seem that you’ve created a new “copy” of booklist, but you haven’t.

You’re not creating a new, independent array. Instead, newBookList is simply a reference to the same array as bookList. This means that any modifications made to newBookList are also reflected in bookList, since both variables point to the same array in memory.

We can prove this as follows:

const bookList = [
"The Hound of the Baskervilles",
"On The Electrodynamics of Moving Bodies",
"Philosophiæ Naturalis Principia Mathematica",
"Disquisitiones Arithmeticae"
];

const newBookList = bookList;


function add(bookName) {
newBookList.push(bookName);
}

add("A Brief History of Time");


console.log(newBookList);
console.log(bookList);

In this case, you’d find BOTH console logs, for bookList AND newBookList to show the same output….

[ 'The Hound of the Baskervilles',
'On The Electrodynamics of Moving Bodies',
'Philosophiæ Naturalis Principia Mathematica',
'Disquisitiones Arithmeticae',
'A Brief History of Time' ]

In order to make a copy of the array, we cannot just do this…

const newBookList = bookList;

To create a new array that is a copy of bookList, and thus won't affect the original bookList when modified, you can use methods like slice() (which creates a shallow copy of an array) or the spread operator (...). For example:

// using slice()
const newBookList = bookList.slice();


// using the spread operator:
const newBookList = [...bookList];

--

--

Jeff P
Jeff P

Written by Jeff P

I tend to write about anything I find interesting. There’s not much more to it than that really :-)

No responses yet