Updating value of local variable inside function is also changing value of global variable

Dear All,

I’ve below code

// 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 (bookList, bookName) {
  let bookListInsideFunction = new Array();
  bookListInsideFunction = bookList;
  bookListInsideFunction.push(bookName);
  return bookListInsideFunction;
  
  // Add your code above this line
}

When I call function add, it’s observed that even global variable bookList value is getting updated. Even when I’m doing action on local variable only.

Please clarify this mystery

It is because this doesn’t make a copy, just a new reference
To copy an array you need to use slice(), concat() or the spread operator
You also don’t need the line where you create new Array(), you can just initialise a variable with value of copy of the array you want to copy

2 Likes

Hello my friend, take a look at these articles. They might help you understnd




https://www.samanthaming.com/tidbits/35-es6-way-to-clone-an-array

1 Like

@ilenia @zebedeeLewis Thanks for detailed clarifications.

Regards,
Vikram

1 Like

Use the spread operator so that it doesn’t refer to the original array.

bookListInsideFunction = [...bookList];

You can also do it in a single line:

function add (bookList, bookName) {
  return [...bookList, bookName];
}

// or

const add = (bookList, bookName) => [...bookList, bookName];

This creates a new array and spreads the original array items and then adds the new book to the end of the array.

1 Like