Tell us what’s happening:
So my code here works, but it took me a while to figure out and brings up a question about data types.
I had originally tried to just declare the variable newArr
by assigning the value of bookList
like so:
let newArr = bookList;
but working on the new array kept mutating the original array bookList
. So I ended up creating a new empty array and then pushing each of the items from the original array into it as you can see below. It seemed like a bit of an excessive approach, but it also seemed necessary.
Am I right in thinking that this is because arrays are “reference” data types and not “primitive” – and what exactly does this mean? I thought I was only changing the new variable I had declared within the function, but that wasn’t what the test results said.
I’d greatly appreciate any clarification or pointers to helpful resources since I am still trying to wrap my head around these two basic types of data in Javascript.
Thanks!
George
Your code so far
// 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 (currentBooks, bookName) {
let newArr = [];
currentBooks.forEach(book => newArr.push(book));
newArr.push(bookName);
return newArr;
// Change code above this line
}
// Change code below this line
function remove (currentBooks, bookName) {
let newArr = [];
currentBooks.forEach(book => newArr.push(book));
let book_index = newArr.indexOf(bookName);
if (book_index >= 0) {
newArr.splice(book_index, 1);
return newArr;
// 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);
console.log(newerBookList);
console.log(newestBookList);
Your browser information:
User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/83.0.4103.61 Chrome/83.0.4103.61 Safari/537.36
.
Challenge: Refactor Global Variables Out of Functions
Link to the challenge: