Tell us what’s happening:
I already solved this on my own but I would like some clarification so that I might better understand the circumstances of why my first attempt to solve this failed.
In the add function I wrote let newArr = bookList;
and tried to finish the add function modifying the newArr
variable that I declared inside of the function but noticed that the Global variable bookList was being modified as well. The result was , the book name argument would show up twice at the end of the global variable and the local variable.
So my question is:
was this happening because arrays are passed by reference and the local variable I declared was tied to the global variable? did setting newArr equal to book list make it a pointer?
I hope I made my question clear, and thank you for taking time to read this.
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 (arr, bookName) {
let newArr = arr.slice();
newArr.push(bookName);
return newArr;
// Change code above this line
}
// Change code below this line
function remove (arr,bookName) {
var book_index = bookList.indexOf(bookName);
if (book_index >= 0) {
let new_arr = arr.slice();
new_arr.splice(book_index, 1);
return new_arr;
// 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(bookList);
console.log(newBookList)
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36
.
Challenge: Refactor Global Variables Out of Functions
Link to the challenge: