Hello this is an exercise from one of freecodecamps challenges. The challenge requires me to modify the given code to remove dependecy on the global variable. I am trying to spread the input array but i keep getting a type error, note the solution to this particular exercise is almost identical to my code yet theirs doesnt receive a type error when using the spread operator. Is there something I'm missing? First my code:
// 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 (arr,bookName) {
let arrCopy = arr.push(bookName);
return arrCopy;
// Change code above this line
}
// Change code below this line
function remove (arr,bookName) {
let newArr = [...arr];
if (newArr.indexOf(bookName) >= 0) {
newArr.splice(newArr.indexOf(bookName),1);
return newArr;
}
}
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);
Now their solution that doesn't invoke a type error:
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 bookName
// Add your code below this line
function add(arr, bookName) {
let newArr = [...arr]; // Copy the bookList array to a new array.
newArr.push(bookName); // Add bookName parameter to the end of the new array.
return newArr; // Return the new array.
}
/* 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) {
let newArr = [...arr]; // Copy the bookList array to a new array.
if (newArr.indexOf(bookName) >= 0) {
// Check whether the bookName parameter is in new array.
newArr.splice(newArr.indexOf(bookName), 1); // Remove the given paramater from the new array.
return newArr; // Return the new array.
}
}
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);
Is there a difference? I have been looking at this for far too long and decided to seek help here