Help~~Help~~Refactor Global Variables Out of Functions

Help~~Help~~Refactor Global Variables Out of Functions
0.0 0

#1

Tell us what’s happening:
HelpHelpHelp~~
what’s wrong with my code???

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 (bookName) {
  
  let aa=[...bookList];
  return aa.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 (bookName) {
  let aa=[...bookList];
  if (aa.indexOf(bookName) >= 0) {
    let bb=aa.indexOf(bookName);
    aa.splice(bb,1);
    return aa;
    // 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 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 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

Remember that the push method itself returns a number representing the length of the array after the new element is added. So, your function is returning a number instead of an array.

Also, your functions are missing a parameter before bookname. Look at the function calls in the bottom section of code. The function is being passed two arguments. Your current functions violate the principal of “Declare function arguments - any computation inside a function depends only on the arguments, and not on any global object or variable.”


#3

@randelldawson thanks,man, i fixed my code, and pass the challenge,

function add (bookList, bookName) {

return bookList.concat(bookName);
}

function remove (bookList,bookName) {
let aa=[…bookList];
if (aa.indexOf(bookName) >= 0) {
aa.splice(aa.indexOf(bookName),1);
return aa;
}
}


#4

@bigfish258: Though I know it works, why does your solution work?

Thankee!