Refactor Global Variables Out of Functionshelp

Refactor Global Variables Out of Functionshelp
0

#1

What am i doing wrong here i dont get 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 (Windows NT 6.1; Win64; x64) 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

The problem is you are changing the global variable bookList. instead you should copy the array to another variable inside your function, i recommend reviewing the lecture about array spread
Lectures are:
Copy Array Items Using slice()
PassedCopy an Array with the Spread Operator

You shoul also look to this part of your code:

return arr.splice(0, 1, bookName);


#3

i am splicing the argument,not bookList,how am i changing bookList?


#4

The argument here is actually the reference to the bookList

Print bookList variable to your console before and after changing


#5

the challenge says not to change the global variable bookList so i passed bookList as an argument and i spliced the argument,does that impact the global variable aswell?


#6

Yes, you should copy the array to another variable inside your function so that function does not change the variable after execution