Why does the bookList array changes in this code and adds "hacked" to it?

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

function add(added,bookName){
added = bookList;
added.push(bookName);
return added;
}

console.log(add(bookList,“hacked”))

console.log(bookList)

its because of the way scope works. had the booklist been passed into the func and assigned to a parameter, and that changed, the orig would have been untouched. But both sides are sharing the same global value. For fun, change that line to added = […booklist];

1 Like

JavaScript arrays and objects are stored by reference, so the line above just assigns the reference to the bookList array to added. Now the reference the same array. If you make push anything to added, it is the same as if you were to have pushed the same thing to bookList. You want to make a copy of the elements in bookList and assign those to an new array named added. @snowmonkey has shown you one way of doing this for this particular array.

2 Likes