Refactor Global Variables Out of Functions - How to stop global variable from changing?

Tell us what’s happening:
My functions for this challenge seem to be working, but I don’t really understand how to make it so the bookList array doesn’t get changed in the end. The solution seems like it would be simple but I can’t seem to figure it out myself.

Here’s what I have 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) {
  arr = [...arr, bookName];
  return arr;
  // 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 someFunction = function (e) {
    return e = bookName;
  }

  if(arr.some(someFunction)){
    arr.splice(arr.indexOf(bookName), 1);
    return arr;
  }
  
}

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/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51.

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

i see you are using splice at one point. Splice actually modifies the array you use it on so that’s why you want to switch to using something like slice or the spread operator to make a copy of the array first.

You can look up how to use slice and/or the spread operator in the curriculum or you can google these.

Thanks for the help, I ended up rewriting the remove function with slice instead of splice and it worked out.

function remove(arr, bookName) {
  let array1 = arr.slice(0, arr.indexOf(bookName));
  let array2 = arr.slice(arr.indexOf(bookName) + 1);
  let newArray = array1.concat(array2);
  return newArray;
}
1 Like

Those who don’t know why a copy of the bookList is necessary can read this article for a explanation: https://codeburst.io/explaining-value-vs-reference-in-javascript-647a975e12a0

1 Like

Very important thing. It is also good to compare this challenge with this one :"Functional Programming: Pass Arguments to Avoid External Dependence in a Function ".