Why is this not working?(Refactor Global Variables Out of Functions)

Tell us what’s happening:

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 bookName

// Add your code below this line
function add (arr,bookName) {
let newarr=arr
newarr.push(bookname)

return newarr;

// 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) {
let newarr=arr
var book_index = newarr.indexOf(bookName);
if (book_index >= 0) {

  newarr.splice(book_index, 1);
  return newarr;

  // 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);

Challenge: Refactor Global Variables Out of Functions

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

You have a few issues.

Read my comment/hint in the code above.

let newarr=arr

This is not doing what you think it is. This is not how you make a copy of an array. You have learned how to do this in previous challenges, so it is just a matter of refreshing your memory on the subject (Google can be of help here too).

1 Like

thank you,ill just restart the whole section i think…
i didnt code for two days and i feel lost lol,forgot so many stuff .

1 Like

ok so after taking your advice Randell , i googled why let newarr=arr doesnt work. ill leave a link for that in here in case someone else does the same mistake https://stackoverflow.com/questions/7486085/copy-array-by-value

also,i tried to “debug” my code by adding console.log(newarr) at the end to see the value of my new array not realizing i’m calling a variable that was declared inside a function.
took me another 15 min of staring the code to realize that, once i deleted that the tests passed. tomorrow ill do better hopefully

1 Like

FYI - In the Basic Data Structures section, there is a challenge named Copy Array Items Using slice which explains how to make a copy (shallow) of an array.

1 Like