Refactor Global Variables Out of Functions help needed

Refactor Global Variables Out of Functions help needed
0

#1

Trying really hard to work this out without help but I can’t. Why isn’t this code working?

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

// 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 tempArr = [...bookList];
  return tempArr.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 (bookList,bookName) {
  let tempArr = [...bookList];
  if (tempArr.indexOf(bookName) >= 0) {
    let index = tempArr.indexOf(bookName);
    //if bookName is in the array basically
    return tempArr.splice(index,1);
    
    // 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);

#2

The push method has a return value and it is a number which represents the length of the array after the new element is added. You end up returning a number instead of the array.


#3

I figured out what was wrong. But can someone tell me why this doesn’t work:

return tempArr.splice(index,1);

but this does:

tempArr.splice(index,1);
    return tempArr;

#4

The splice method has a return value also. The returned value is an array containing all the elements removed from the array on which splice was called. You are removing one element with your splice, so the return value is an array with that removed element, so your return statement ends up returning an array of the removed element instead of an array without the element.


Slice and Splice: just a question