Refactor variable out of function

Tell us what’s happening:
Passing 3 tests but failing the 4th. Any pointers will be appreciated.

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
function add (list, bookName) {
list = [...bookList]
list.push(bookName);
return list;

// Change code above this line
}

// Change code below this line
function remove (list, bookName) {
list = [...bookList]
var book_index = list.indexOf(bookName);
if (book_index >= 0) {

  list.splice(book_index, 1);
  return list;

  // 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 (Linux; Android 10; SM-A908B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.110 Mobile Safari/537.36.

Challenge: Refactor Global Variables Out of Functions

Link to the challenge:

I don’t think you should be referencing the global variable at all.

1 Like

If i dont reference it, how do i get access to the contents of bookList?

The current booklist to modify is passed in as the arr


Rewrite the code so the global array bookList is not changed inside either function. The add function should add the given bookName to the end of the array passed to it and return a new array (list). The remove function should remove the given bookName from the array passed to it.

Note: Both functions should return an array, and any new parameters should be added before the bookName parameter.

Actually I had missed the (list) bit. Let me retry

I named my array ‘list’, still getting same result.

What i dont get is: if i dont copy bookList into a new array how does the new array(list) get to have the same contents as bookList. Pardon my slowness.

look at how the functions are called, you don’t need any global variable inside your function because if you do if a different list of books is used your function doesn’t work anymore

2 Likes

Thanks @ilenia
So I have understood your explanation for not having the global variable inside a function.
But you also pointed out something I was not getting. I guess I was focusing too much on the functions without looking at the calling.
Even though there is no reference of bookList inside the functions, bookList is referenced when the functions are called. This answers my question.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.