Functional Programming - Refactor Global Variables Out of Functions

Tell us what’s happening:
Describe your issue in detail here.
i need to know why my code didn’t pass the first test in this challenge

  **Your code so far**
// The global variable
const 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(booklist , bookName) {

booklist.push(bookName);
return booklist;

// Change code above this line
}

// Change code below this line
function remove(booklist,bookName) {
const book_index = booklist.indexOf(bookName);
if (book_index >= 0) {

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

  // Change code above this line
  }
}

console.log(bookList);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.81 Safari/537.36 Edg/104.0.1293.54

Challenge: Functional Programming - Refactor Global Variables Out of Functions

Link to the challenge:

If I put this at the bottom of your code:

console.log('global', bookList);
const returnedList = add(bookList, 'The Book');
console.log('returnedList', returnedList);
console.log('global', bookList);

I see that you are changing the global variable. This is the output:

global [ 'The Hound of the Baskervilles',
  'On The Electrodynamics of Moving Bodies',
  'Philosophiæ Naturalis Principia Mathematica',
  'Disquisitiones Arithmeticae' ]
returnedList [ 'The Hound of the Baskervilles',
  'On The Electrodynamics of Moving Bodies',
  'Philosophiæ Naturalis Principia Mathematica',
  'Disquisitiones Arithmeticae',
  'The Book' ]
global [ 'The Hound of the Baskervilles',
  'On The Electrodynamics of Moving Bodies',
  'Philosophiæ Naturalis Principia Mathematica',
  'Disquisitiones Arithmeticae',
  'The Book' ]

Notice that the last one should match the first one. The only thing that should be changed is the one that is returned.

Remember that when you pass an array (or object or any reference type) to a function, you are passing the reference, the memory address. Any changes you make at that memory address will change what any reference to that memory address sees.

If I give two people the address to the same house and I tell one of them to go mow the lawn there, the second person will see that the lawn is mowed. I didn’t create a new house, I just gave a copy of the address.

Think on that. See if you can find the problem. If not, come back and we’ll see if we can get you closer.

thank you its clear now

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.