Refactor Global Variables Out of Functions

Could anyone tell me why the codes below failed to pass this challenge? Many thanks!

bookList should not change and still equal ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"] .

// The global variable
const 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(arr, bookName) {
  let newList = [];
  newList.push(bookName)
  return arr.concat(newList);
  
  // Change code above this line
}

// Change code below this line
function remove(arr, bookName) {
  const book_index = bookList.indexOf(bookName);//1
  if (book_index >= 0) {
    arr.splice(book_index,1)
    return arr;

    // Change code above this line
    }
}

Please provide a link to the challenge.

I might also suggest googling “mdn splice” and reading about it.

There you go -

thanks.

I did and also get the results I want, but couldn’t figure out why my code failed to pass - bookList should not change and still equal ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"] .

You have a few issues here:

function remove(arr, bookName) {
  const book_index = bookList.indexOf(bookName);//1
  if (book_index >= 0) {
    arr.splice(book_index,1)
    return arr;

    // Change code above this line
    }
}

One issue is that you should not be referring to the global variable.

The other issue is splice. Google that mdn article and reread the first 9 words of the first paragraph.

And remember that passing in an array does not make a new copy - reference types (including objects and arrays) are passed by reference (memory address). If I write the address to my house on two slips of paper, I do not have a new house, just two copies of the address that point to the same thing.

The other problem with this function is what does it return if the index isn’t found? I don’t think that breaks a test, but it should.

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