Functional Programming Good or Bad Practice

Can someone explain to me why

var newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies'); does not work?

Am I using bad practice/methods in functional programming?


// the global variable
var bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];

/* This function should add a book to the list and return the list */
// New parameters should come before the bookName one

// Add your code below this line
function add (bookList, bookName) {
  let bList = bookList;
  bList.push(bookName);
  return bList
  // Add your code above this line
}

/* This function should remove a book from the list and return the list */
// New parameters should come before the bookName one

// Add your code below this line
function remove (list, bookName) {
  let bList = list
  if (bList.indexOf(bookName) >= 0) {
    let startIndex = bList.indexOf(bookName)
    bList.splice(startIndex, 1);
    return bList
        // Add your code above this line
    }
}

var newBookList = add(bookList, 'A Brief History of Time');
var newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies');
var newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies');
console.log(newestBookList)

Maybe it’s the remove function, since it only returns the list if it finds the item to remove, otherwise it returns undefined

This does not create a copy. Any changes to bList will affect the global bookList.

1 Like

Link to the problem: https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/functional-programming/refactor-global-variables-out-of-functions