Functional Programming - Refactor Global Variables Out of Functions

Tell us what’s happening:
Describe your issue in detail here.

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(newarr,bookName) {
 newarr = [...bookList]
  newarr.push(bookName);
  return newarr;
  
  // Change code above this line
}
console.log (add());

// Change code below this line
function remove(newarr,bookName) {
  newarr = [...bookList]
  const book_index = newarr.indexOf(bookName);
  if (book_index >= 0) {

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

    // Change code above this line
    }
    console.log(remove())
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36

Challenge: Functional Programming - Refactor Global Variables Out of Functions

Link to the challenge:

In general, you don’t want to alter the arguments passed into a function when they are arrays/objects because they are passed by reference. Let’s look at how the first test is calling this function:

add(bookList, "A Brief History of Time")

So that means the global array bookList is being passed into the function as the first arg. Thus, your add function will alter the global bookList array.

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