Question - Refactor Global Variables Out of Functions

Tell us what’s happening:
In order to not mutate the original “bookList”, I copied the contents of “bookList” to a new variable called “newList”

However this isn’t working. Can I get a hint as to what I should look into?

Thank you!

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"];

// Change code below this line
var newList = bookList;

function add (a, b) {
newList.push(b);
return(newList);
// Change code above this line
}

// Change code below this line
function remove (a, b) {
var book_index = newList.indexOf(b);
if (book_index >= 0) {
  newList.splice(book_index, 1);
  return(newList);
  // Change 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/80.0.3987.132 Safari/537.36.

Challenge: Refactor Global Variables Out of Functions

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

This is exactly one of the points of this challenge. If you simply try to write
var newList = bookList;
it will not create separate copy of the bookList, but will make variable newList point to the same object as variable bookList. As lists can be mutated, later changes to the list using one of the variable name will be “visible” also when using the other variable.

There are many different ways to do this. One of them is using particular new feature introduced in ES6, other one will be used in one of the further challenges in the functional programming section.

1 Like