Not changing the globals

Tell us what’s happening:

i dont see why this is changing the global variables

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"];

// Change code below this line
function add (bookName) {
let changedlist = bookList;

return changedlist.push(bookName);

// Change code above this line
}

// Change code below this line
function remove (bookName) {
var book_index = bookList.indexOf(bookName);
if (book_index >= 0) {
let changedlist = bookList;
  changedlist.splice(book_index, 1);
  return changedlist;

  // 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 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36.

Challenge: Refactor Global Variables Out of Functions

Link to the challenge:

This doesn’t create an independent copy of bookList. When you assign variables to an object (arrays are objects) they all point to the same object. Changing one, changes this shared object.

If thats true this is a needlessly confusing thing about js.

arrays and objects are referenced values. if you really want to copy, you can use the spread operator copiedArr = [...nameOfArray].

It’s actually true of many languages. Objects are accesses “by reference” (the memory location) rather than “by value” (unlike primitive data types).

why only array object but not variables? like variables should work the same way as objects.

Any variable created by the JS engine are primitive. Example are: strings, numbers, Booleans, null, undefined, symbol. They are stored in the stack (the short memory) and can be removed easily and recreated. Copying these, copies it’s value.

Referenced values on the other hand are hard to create, and are stored in the heap. They use more memory, space and so on. So i suppose this is why are are made to behave that way

1 Like

In programming languages, data is stored in different types. Data types aren’t usually covered in early JavaScript lessons because JS is weakly typed.

You’ve already encountered some differences between types. Remember how strings are immutable?

Each data type has its own qualities:
The six basic JavaScript types
JavaScript data types and data structures