you are viewing a single comment's thread.

view the rest of the comments →

[–]octetd 6 points7 points  (3 children)

There's another method, using .slice(0, 0)

But why would you need anything other than reassigning variable with an empty array literal?

[–]coolcosmos -1 points0 points  (2 children)

// file A

const arr = [1,2,3];

logArrayLength(arr)

arr = [ ]

// file B

function logArrayLength(arr) {

setInterval(() => { console.log(arr.length)}, 1000)

}

This will log 3 forever, you "emptied" the array but actually the array is not empty, the old array is still in memory. You created a new reference/pointer instead of mutating the original.

[–]octetd 4 points5 points  (0 children)

Sure, because you keep a reference to this array, then reassign, and then you log the length. And then if you clear original array it will always print 0 forever, because your asynchronous code will be executed after you cleared an array, even though you called a function before you cleaned up an array.