// The global variable var bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "PhilosophiƦ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]; // Change code below this line function add (bookName, test) { console.log('t', bookName) let newB = bookName; newB.push(test) return newB; // Change code above this line } // Change code below this line function remove (bookName) { var book_index = bookList.indexOf(bookName); if (book_index >= 0) { bookName.splice(book_index, 1); return bookName; // Change code above this line } } var newBookList = add(bookList, 'A Brief History of Time'); var newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies'); var newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies'); console.log(newBookList, newerBookList, newestBookList) console.log(bookList);
t [ "The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "PhilosophiƦ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae" ] t [ "The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "PhilosophiƦ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"
How come there is the two strings; “A Brief History of Time” and “A Brief
History of Time” is it saving the value and using it again? How would it
remember that there was a brief history in time in the last function call?
The function call in the third global variable is add(bookList, ‘A Brief
History of Time’) so what is happening?
If you don’t understand what I am saying, basically, I am trying to fix the
add() function and it’s working but it’s run twice because it’s assigned to
two variables and the problem is that in the newestBookList, the add()
function added the string, but it added the string to the array that I made
before in the add() function.
Advertisement
Answer
By the way you have named your variable in the line: let newB = bookName;
, this line of code is not doing what you think it’s doing. It is not creating a new instance of bookName
, it is just assigning to newB
the existing array reference passed in on the bookName
parameter, which is bookList
.
Since you continue to pass in bookList
and do not get a new array reference with something like [...bookName]
or bookName.slice()
, it keeps using that same array with each subsequent call. So it will continue to push values onto the same array. That’s why you’re getting the output you’re getting.
One example of how you can return a new array reference each time is like so:
function add (bookName, test) { console.log('t', bookName) let newB = bookName.slice(); // generates a new array with the same elements newB.push(test) return newB; }