To make an already existing array empty in JavaScript, you can use several methods to remove all elements from the array:
You can set the length property of the array to 0. This method truncates the array, effectively removing all its elements:
let arr = [1, 2, 3]; arr.length = 0; // Makes the 'arr' array empty
You can use the splice() method to remove all elements from the array starting from index 0:
let arr = [1, 2, 3]; arr.splice(0, arr.length); // Removes all elements from 'arr'
You can repeatedly use the pop() method in a loop to remove elements until the array becomes empty:
let arr = [1, 2, 3]; while (arr.length > 0) { arr.pop(); }
You can assign a new empty array [] to the existing array variable. This reassigns the variable to reference a new empty array, effectively emptying the original array:
let arr = [1, 2, 3]; arr = []; // Assigns 'arr' to a new empty array, making the original array empty