Refactor Global Variables Out of Functions pass by value or by reference

Tell us what’s happening:

Your code so far


// 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 (bookName) {
  
  return bookList.push(bookName);
  
  // 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 (bookName) {
  if (bookList.indexOf(bookName) >= 0) {
    
    return bookList.splice(0, 1, bookName);
    
    // 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(bookList);

Your browser information:

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

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

Does Java Script pass arrays( which are objects by the way) by value or reference? I am asking this because on this problem when we pass the array to the add or remove methods, I am wondering if the functions get a copy of the array or the same array?

So it’s an interesting question. If we have saved a reference to it, it is passed by reference. If we are simply creating the array in the function parameter and passing that, we pass it by value. But you have a larger problem going on.

Your add() and remove() are being called with two parameters, booklist and bookname, but you only accept one.

You’ll need to factor to receive a booklist AND a bookname, clone a copy of the booklist (rather than referencing the global bookList), and do your add/remove on that cloned copy. Then, return that clone.

Thank you very much your reply!