Understand the tricky behavior while making array empty and learn how to fix it.

By: Yogesh Chavan | FrontEnd Weekly.

Many times there comes a time when we want to remove all the elements of array may be we are having list of todos and we want to remove all the todos at once.

Consider, we have list of items

let items = ["tea", "coffee", "milk"];

Then to remove all the elements from the array we set it to an empty array like this

items = []

This works perfectly and you will find it used all the time. But there is an issue with this.

Consider, below code

let items = ["tea", "coffee", "milk"];let copy = items;

Here we are creating a copy variable and assigns it a reference of itemsarray so copy actually points to the items array.

Now, let’s check their individual values

console.log(items); // ["tea", "coffee", "milk"]console.log(copy); // ["tea", "coffee", "milk"]

This is as expected.

Read the full article here.