jorgenmodin.net
Search

Don't use A.slice(0) to empty an array in Javascript

published May 10, 2016 11:30   by admin ( last modified May 10, 2016 11:32 )

As explained on StackOverflow:

This code will set the variable A to a new empty array. This is perfect if you don't have references to the original array A anywhere else because this actually creates a brand new (empty) array. You should be careful with this method because if you have referenced this array from another variable or property, the original array will remain unchanged. Only use this if you only reference the array by its original variable A.

Instead use:

A.length = 0

or:

A.splice(0,A.length)