Hey everyone! Today, we will see how we can empty an array in JavaScript. The most obvious method is to simple reassign the array variable to an empty array, which for all intents and purposes will usually work for most of the cases but there is a minor pitfall here. if you have created a new reference variable for original array reference variable, then upon setting the original array as empty, the new reference will still remain unchanged. For example here we created a new reference to the array names called namesCopy and if we reassign names as an empty array the copy will persist the original array. To avoid this edge case a better solution is to simple set the length property of the array as zero. Not only will this clear the original array but it will also empty all the other reference variables which point to the original array. Lets use the same example but this time we will set the length of the original array as 0 and as you can see the array references were also emptied.
コメント