How do I empty an array in JavaScript?
Clearing an array in JavaScript can be done in multiple ways, each suitable for different scenarios. I will introduce several common methods with examples.Method 1: Set Array Length to 0This is the simplest and fastest approach. By directly setting the array's property to 0, you can immediately clear the array.Method 2: UsingThe method modifies the array's content, allowing you to delete, replace, or add elements. To clear the array, remove all elements starting from index 0.Method 3: Reassign to a New Empty ArrayDirectly reassign the array to a new empty array, which discards the original reference and clears the array content.Method 4: UsingAlthough less efficient, you can use a loop combined with to clear the array. The method removes the last element and returns it.Choosing the Right MethodFor quick clearing without reference concerns, setting is optimal.If the array is referenced by multiple variables and you want all references to point to an empty array, use or a loop with .If you simply want to discard the old array and create a new one, directly reassign to .These methods cover various scenarios, and you can select the most appropriate method based on your specific needs and context.