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 clipboard
  • Setting 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 clipboard
  • Array 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 clipboard
  • Lodash'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
Rafael Caferati

Full Stack Web Developer, UI/UX Javascript Specialist.

<[{ Part-time developer – full-time geek }]>

Avatar