Functional Programming - Refactor Global Variables Out of Functions

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

1 Like

It is showing that it has been changed. The original bookList had the book “On The Electrodynamics of Moving Bodies” in it. You removed it using the remove function. All of the console logs you are doing come after removing that book, so they all show the bookList without that book and thus are all the same.

Try changing let myBookList = bookList; to let myBookList = [...bookList]; and then see what your console logs produce.

Sorry, my bad, I must be too tired yesterday. I actually typed let myBookList = […bookList], at VSCode as you mentioned, but use let myBookList = bookList at practice window, somehow just couldn’t find the difference out. Thank you for your reply. :flushed:

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.