To wipe an array in JavaScript, you remove every item but keep the variable. JavaScript offers a few ways to do this. This post looks at various ways to clean out an array showing you how to do it with code steps.
1. Making the Length Zero
It’s quick and popular to just set the length of an array to zero.
Here’s how:
<script>
let arr = [1, 2, 3, 4 5];
arr.length = 0;
console.log(arr); // Output: []
</script>
2. Using splice()
The splice()
function is awesome for clearing an array too.
The splice()
function clears out an array starting with the first item.
Example:
<script>
let arr = [10, 20, 30 40];
arr.splice(0 arr.length);
console.log(arr); // Shows: []
</script>
3. Whip Up a While Loop with pop()
Unwind an array piece by piece using a while
loop paired with a pop()
action.
Example:
<script>
let arr = ['a', 'b', 'c'];
while (arr.length > 0) {
arr.pop();
}
console.log(arr); // Shows: []
</script>
4. Switch it Up to a Blank New Array (But be Smart About It)
Go ahead and slap a blank new array onto your variable. However, remember this ain’t gonna mess with anything that already points to the old array.
Peep This:
<script>
let arr = [100, 200 300];
let ref = arr;
arr = [];
console.log(arr); // Yo, check it: []
console.log(ref); // Still hanging onto: [100 200 300]
</script>
5. Throw length
Into the Mix Inside a Function
Dropping length
in a function is slick when you’ve gotta deal with functions or reset arrays that everyone can get at.
Look at This Example:
<script>
let numbers = [9, 8, 7];
function resetArray(list) {
list.length = 0;
}
resetArray(numbers);
console.log(numbers); // Shows: []
</script>
Wrap-Up
Time to review some methods to clear an array in JavaScript:
- Setting
list.length = 0
— It’s quick and gets the job done. - Using
list.splice(0 list.length)
— This works great if you gotta keep links. - Running a
while
loop withlist.pop()
— This one’s cool if you’re learning. - Reassigning
list = []
— It’s easy peasy but won’t update other linked arrays. - Popping these tricks into functions — Super handy for tidying up arrays in your tools.
Select the technique that suits your unique scenario the best.