This is what I have so far, I understand I have to make it so that bookList is not known to the functions in any way except through a new variable which I have created for both functions and assigned them the contents of bookList through the spread operator. I have also tried other methods to no avail. Any suggestions? Thanks!
// 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
function add (bookName) {
let a=[...bookList]
a.push(bookName);
return a;
// Change code above this line
}
// Change code below this line
function remove (bookName) {
let b=[...bookList]
var book_index = b.indexOf(bookName);
if (book_index >= 0) {
b.splice(book_index, 1);
return b;
// 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/86.0.4240.75 Safari/537.36.
Challenge: Refactor Global Variables Out of Functions
But the original code in the challenge doesn’t affect the global variable either, right? I have tried saving bookList into another variable as you can see and it’s still not going through. I know the whole point of the challenge is to show how to indirectly use a global variable in the code but am I missing something?
Ahhh, the previous challenges were getting me to use these variables as arguments but I still didn’t understand why I would use a global variable which is already declared, as an argument when I can just declare it again inside the function without having to pass it in as an argument? I feel like this will be confusing when I apply it further down the line. I’ll self educate on the topic for sure. I appreciate the help.
// Change code below this line
function add (bookList,bookName) {
bookList=[...bookList]
bookList.push(bookName);
return bookList;
// Change code above this line
}
// Change code below this line
function remove (bookList,bookName) {
var book_index = bookList.indexOf(bookName);
if (book_index >= 0) {
bookList=[...bookList]
bookList.splice(book_index, 1);
return bookList;
// Change code above this line
}
}
You got it! With function arguments we can write independent functionality that doesn’t know or care about the code around it. Now your function knows that when it is called it will be given a book list and a book name. It doesn’t have to find where those originally were created.