Refactor Global Variables Out of Functions I have a question!

// My 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 (arr, bookName) {
  let newArr = [...arr];
  newArr.push(bookName);
  return newArr;
  
  // 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 (arr, bookName) {
  let newArr = [...arr];
  if (newArr.indexOf(bookName) >= 0) {
    newArr.splice(newArr.indexOf(bookName), 1);
    return newArr;
    
    // 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(newBookList);
console.log(bookList);

The result will be two arrays of ‘newBookList’ and ‘bookList’. I understood the code above, but I still have a question like this: if I change the ‘add’ function as follows:

function add (arr, bookName) {
  let newArr = [...arr];
  return newArr.push(bookName);
}

The result will now be 5 and the ‘bookList’ array. So what’s the difference here?

your new add function looks like it’s returning the length of newArr after your bookName is appended.

1 Like

Oh, i got it, thank you.