How do you clear or empty an existing JavaScript array efficiently? | A1Lab@FahadM to JavaScriptEnglish •
edit-2
11 days ago

How do you clear or empty an existing JavaScript array efficiently?

message-square
0

Set **array.length = 0** to clear all elements in place in **$O(1)$ time** while preserving any existing references to the array, or reassign **array = []`** if no other variables reference it.

In-Place Clear vs. Reassignment

let items = [1, 2, 3, 4, 5];
const ref = items;

// 1. Clear in place (empties both 'items' and 'ref' instantly)
items.length = 0;
console.log(items, ref); // [] []

// 2. Reassign to a fresh empty array (does NOT affect existing references)
items = []; '