Javascript empty an existing array
- JAVASCRIPT
- ARRAY METHODS
- CODING TIPS
Published on 2018-08-14
A couple methods on how to empty an array in Javascript
Consider var my_array = [1, 2, 3]; and var other_array = my_array;New empty array references remain unchanged
Be aware that if you had any references to my_array they'll remain unchanged as you would be pointing my_array to a newly created one.
my_array = []; // other_array is still [1, 2, 3]
Copy code to the clipboardSetting array.length to 0
Be aware that as we're updating the value, all references to my_array will still point to the same changed array.
my_array.length = 0; // other_array is now empty []
Copy code to the clipboardArray splice() method
Be aware that as we're updating the value, all references to my_array will still point to the same changed array.
my_array.splice(0, my_array.length); \n // other_array is now empty []
Copy code to the clipboardLodash's remove() method
Be aware that as we're updating the value, all references to my_array will still point to the same changed array.
_.remove(my_array, undefined); \n // other_array is now empty []
Copy code to the clipboard
Have you enjoyed the read? Please show your support by sharing it with the world 🙌🏻Share Share Share