Functional Programming : Refactor Global Variables Out of Functions

Hello, It’s my first time touching Java and i’m following the course on FCC.
I have a really hard time finding the issue with my code for this challenge…
Here is the link to the challenge :

To quickly explain the issue i have, it’s about the first test. the global variable bookList should stay unchanged, but it’s not being accepted. Even though console.log(bookList) shows me what’s asked… The rest are OK.

Here’s the code;

// 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(bookArray,bookName) {
  let listAdd = bookArray; // Creating another variable to keep bookList unchanged
  listAdd.push(bookName);
  return listAdd;
  
  // Change code above this line
}

// Change code below this line
function remove(bookArray,bookName) { 
  let Listing = bookArray; // creating another variable to keep bookList unchanged
  const book_index = Listing.indexOf(bookName);
  if (book_index >= 0) {

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

    // Change code above this line
    }
}
console.log(bookList) // it gives me what is tasked, [ 'The Hound of the Baskervilles','On The Electrodynamics of Moving Bodies','Philosophiæ Naturalis Principia Mathematica','Disquisitiones Arithmeticae' ]
// the only change is from "" to ''... 

Thanks for any answer to enlighten me, as i’m really a newbie i would prefer if you could start with simple things.

I resolved it, the issue was with when i let the variable inside my function.

It did not work with :
let newArr = arr;

But worked with :
let newArr = […arr];

Could someone explain why it changes like that? I mean, is there cases where using the first line would bring issues or is it just a “law”?

An array isn’t a primitive value, it’s an object. If you assign an array to a variable, what is assigned is a reference to the array object.

This line:

let newArr = arr

Is just saying “assign the reference to arr to the variable newArr”. The values inside the array are exactly the same, the new reference still points to the same thing.

If you want to copy the array values, then above is not copying the array. It’s just copying the reference, the array is exactly the same.

2 Likes

Thank you very much !

1 Like

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