Refactor Global Variables Out of Functions- Use of indexOf

Refactor Global Variables Out of Functions- Use of indexOf
0

#1

I am working on this challenge but stuck. The error message says arr.indexOf is not a function.
Could you tell me what is wrong with my code and some hints to fix it?
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"];

/* This function should add a book to the list and return the list */
// New parameters should come before the bookName one

// Add your code below this line
function add (arr, bookName) {
  
  return arr.push(bookName);
  
  // Add your code above this line
}

/* This function should remove a book from the list and return the list */
// New parameters should come before the bookName one

// Add your code below this line
function remove (arr, bookName) {
  if (arr.indexOf(bookName) >= 0) {
    
    return arr.splice(0, 1, bookName);
    
    // Add your 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 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.

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


#2

Actually it is because arr.push() returns a number , so you have to first push the element to arr and return the arr , like this

// Add your code below this line
function add (arr, bookName) {
  
  arr.push(bookName);
  return arr;
  
  // Add your code above this line
}
  1. you should not change the global variable bookList , so create a new local variable inside each method and perform the push and splice operations on them , Like this
// Add your code below this line
function add (arr, bookName) {
  let localArray = [...arr];
  localArray.push(bookName);
  return localArray;
  
  // Add your code above this line
}

Do the same for the remove() also
3) Read up on the splice() , i think you didn’t completely understood its syntax,
for quick refer this

Syntax

array.splice(index, howmany, item1, …, itemX)
Parameter Values
indeX : An integer that specifies at what position to add/remove items, Use negative values to specify the position from the end of the array
howmany : The number of items to be removed. If set to 0, no items will be removed
item1, …, itemX : The new item(s) to be added to the array (OPTIONAL).

For further reference on splice : https://www.w3schools.com/jsref/jsref_splice.asp