Spread operator use

why the code is not passing if I use
bk = bookList;
and why
bk = […bookList]
is working


// 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 (bookList,bookName) {
var bk = [...bookList];
bk.push(bookName);
return bk;
// Change code above this line
}

// Change code below this line
function remove (bookList,bookName) {

var bk = [...bookList];
console.log(11,bk);
var book_index = bk.indexOf(bookName);
if (book_index >= 0) {

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

  // Change 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 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.123 Safari/537.36.

Challenge: Refactor Global Variables Out of Functions

Link to the challenge:

Short answer:
Because […booklist] creates a copy of booklist and assigns it to bk. Which means there’s no copying of the references.

Javascript arrays use references. What does that mean?
It’s an advance topic but maybe this example explains it:
let x = [ 1, 2, 3 ];
let z = x;
z.push(44);

console.log(z);
[1,2,3,44];

console.log(x);
[1,2,3,44]; ???!?

Notice how the 44 got attached to x too? It’s because when you assigned z = x, the references are copied too.

So in your example, when you do var bk = booklist,. you’re modifying the global booklist variable.

1 Like