Tell us what’s happening:
Describe your issue in detail here.
Hi there, I’m new to JavaScript, in chapter “Refactor Global Variable Out of Function”, the hint says:
“…using something like const newArr = arrVar
, where arrVar
is an array will simply create a reference to the existing variable and not a copy. So changing a value in newArr
would change the value in arrVar
.”
However, I coded it by VSCode as below, and used Chrome console to check it. The console shows either add or remove function, the bookList hasn’t been changed. It seems let myBookList=booklist will actually make a copy of booklist, not just a reference.
Could you tell me if I missunderstand something or what? Why does the Chrome console shows the bookList hasn’t been changed, and on the contrary, the practice console keeps remind me the bookList should not change.
Your code so far
// The global variable
const 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(bookList, bookName) {
let myBookList = bookList;
myBookList.push(bookName);
console.log("bookList: ", bookList, "myBookList: ", myBookList);
return myBookList;
// Change code above this line
}
// Change code below this line
function remove(bookList, bookName) {
let myBookList = bookList;
const book_index = myBookList.indexOf(bookName);
if (book_index >= 0) {
myBookList.splice(book_index, 1);
console.log("bookList: ", bookList, "myBookList: ", myBookList);
return myBookList;
// Change code above this line
}
}
//add(bookList, "A Brief History of Time")
remove(bookList, "On The Electrodynamics of Moving Bodies")
console.log("final bookList:", bookList);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36
Challenge Information:
Functional Programming - Refactor Global Variables Out of Functions