Refactor Global Variables Out of Functions!

I have redefined the array locally by cloning it, and then performing operations on the cloned array. But the only part of the problem that is solved is that the original array is not changed, but the rest of the parts of the problem dont work. Whats going on?

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 (bookArr,bookName) {
  let books=[...bookArr];
  return books.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 (bookArr,bookName) {
  let books=[...bookArr];
  if (books.indexOf(bookName) >= 0) {
    
    return books.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 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36.

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

You’re returning the return values of push and splice, which are the new length of the array and the deleted elements, respectively, not the resulting array.

You already have the answer, but just to (maybe) make it more clear.

Basically, you just need to return the books array after you have push/splice, instead of returning the methods return value.

/* This returns the push methods return value which is the array length */
function addNumber(number) {
  const numbers = [1, 2, 3]
  return numbers.push(number)
}

addNumber(8) // returns 4 which is the array length
/* This returns the array */
function addNumber(number) {
  const numbers = [1, 2, 3]
  numbers.push(number)
  return numbers;
}

addNumber(4) // [1, 2, 3, 4]

I’d suggest always looking at the docs for the methods. On MDN under the Syntax section for the method, there is a Return value section which shows what the method returns.


oh, got it, I had to return the array, and not just the section
thanks