Functional Programming - Refactor Global Variables Out of Functions

Tell us what’s happening:
One of the parameters in the exercise was to check whether the bookList have been changed. I checked it using “if” statements on the bookList at the start and after running the function and found it was still the same. According to the code, it was true. May I know what is it that I have missed here and why it is not accepted? Thanks.

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
console.log ('bookList Orig:', bookList);
var book1 = bookList;

function add(bookList, bookName) {

  let bookList2 = bookList;
  bookList2.push(bookName);
  return bookList2;

  // Change code above this line
}

// Change code below this line

function remove(bookList, bookName) {

  let bookList2 = bookList;
  const book_index = bookList2.indexOf(bookName);
  if (book_index >= 0) {

    bookList.splice(book_index, 1);
    return bookList2;

    // Change code above this line
    }
}
var book2 = bookList;
console.log ('bookListAfter:',bookList);

if (book1 == book2) {
  console.log (true);
} else {
  console.log (false);
}

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:106.0) Gecko/20100101 Firefox/106.0

Challenge: Functional Programming - Refactor Global Variables Out of Functions

Link to the challenge:

The add function should add the given bookName to the end of the array passed to it and return a new array

let bookList2 = bookList;

This does not copy an array. This copies the reference or address of the array, so both point to the same array. If you change what one points to, what the other points to changes to, because they are pointing to the same thing.

How do you copy the values of an array into a new array?

thank you for the feedback Kevin Smith!

I have input this code

let newBook = [...bookList]

Yes, that is one way to make a shallow copy of an array. Good job.

1 Like

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