Functional Programming - Refactor Global Variables Out of Functions

// 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(bookName) {
let book = bookList;
  book.push(bookName);
  return book;
  
  // Change code above this line
}

// Change code below this line
function remove(bookName) {
  let book = bookList;
  const book_index = book.indexOf(bookName);
  if (book_index >= 0) {

    book.splice(book_index, 1);
    return book;

    // Change code above this line
    }
}

QUESTION

I tried to equate book to bookList. And then work with book. So bookList remains the same. Please what is wrong???

If I understand your question correctly, you want to create a copy of bookList so that the bookList variable does not change and only the new book variable changes?

If that is the case, the issue is that objects like arrays are passed by reference in JavaScript by default. What this means is your new book variable is only referencing the bookList variable instead of making a copy. Any changes you make to the book variable is really just updating bookList.

To create a copy of your array, you will need to use the spread operator (…) which would look like:

let book = […bookList];

You can read more about the spread operator here:
Spread syntax (…) - JavaScript | MDN (mozilla.org)

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