I'm correct? Refactor Global Variables Out of Functions

Tell us what’s happening:
first post here and after a thousand doubts behind,
i’ve found this Solution 2 so elegant and concise
but i have few questions

in add,
is using spread operator to get all the books in the bookList array?
is it coyping them?can we return it without side effect?

in remove,
filter is going to be executed only if there’s an index for book?
why we can’t use spread inside if?
item !== is for not a bookname in the array?
and again how can we return safe ?


Your code so far

function add (list,bookName) {
  return [...list,bookName]
function remove (list,bookName) {
  if (list.indexOf(bookName) >= 0) {
    return list.filter((item)=> item !== bookName);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0.

Link to the challenge:


Is an array of strings


Says “give me the values in that array one by one” (it can’t be used on it’s own to do that, but that is what it does when you use it in the correct context, like:)


Does the same, it gives you the values one by one, but puts them into a new array

[...list, bookname]

Does the same, but puts them in a new array with one value already present.

Note it’s exactly the same in practice as:


Which creates a new array with the new value added to the end.

It’s a new array, so yes. You are copying the values from one array into a new array.

Yes, ie if the name of book is actually in the array. That line could also be written (maybe more clearly) as:

if (list.includes(bookName)) {

That’s exactly the same. It’s also completely unnecessary: if the title isn’t in the list of titles, logically it can’t get filtered out, so nothing will change.

Why would you need to?

Each item is the name of a book, so you are saying “the name of the current book is not the same as the name of the book you want to remove”. Maybe names of parameters used inside the function are not great, I’d maybe say it was a bit clearer if it were more like

function add (bookTitles, bookTitle) {
  return [...bookTitles, bookTitle];
  // Or:
  // return bookTitles.concat(bookTitle);

function remove (bookTitles, bookTitle) {
  return bookTitles.filter((title)=> title !== bookTitle);

filter returns a new array every time, so no issue there