How to quickly clear an array?

👨‍💻 Frontend Developer 🟠 May come up 🎚️ Easy
#JavaScript #Arrays #JS Basics

Brief Answer

Clearing an array can be done in several ways: array.length = 0 (fastest), array.splice(0), array = [] (creating a new array) or while(array.pop()). The choice depends on whether you need to preserve references to the original array.

Recommended methods:

  • array.length = 0 — fastest, preserves references
  • array.splice(0) — universal, returns removed elements
  • array = [] — creates new array, old references remain

What does clearing an array mean

Clearing an array is the process of removing all elements from an array, making it empty. It’s important to understand the difference between clearing an existing array and creating a new empty array.

The reference problem

const originalArray = [1, 2, 3, 4, 5];
const reference1 = originalArray;
const reference2 = originalArray;
 
// If you simply assign a new array
originalArray = []; // ❌ References reference1 and reference2 still point to the old array
 
console.log(reference1); // [1, 2, 3, 4, 5] — old array!
console.log(reference2); // [1, 2, 3, 4, 5] — old array!

Methods for clearing arrays

1. Changing the length property

const numbers = [1, 2, 3, 4, 5];
numbers.length = 0;
 
console.log(numbers); // []
console.log(numbers.length); // 0

Advantages:

  • ✅ Fastest method
  • ✅ Preserves all references to the array
  • ✅ Minimal memory consumption

Disadvantages:

  • ❌ Doesn’t return removed elements
  • ❌ May seem non-obvious

2. The splice() method

const fruits = ["apple", "banana", "orange"];
const removed = fruits.splice(0);
 
console.log(fruits); // []
console.log(removed); // ["apple", "banana", "orange"]

Advantages:

  • ✅ Returns removed elements
  • ✅ Preserves references to the array
  • ✅ Standard array method

Disadvantages:

  • ❌ Slower than length = 0
  • ❌ Creates new array with removed elements

3. Creating a new array

let colors = ["red", "green", "blue"];
colors = [];
 
console.log(colors); // []

Advantages:

  • ✅ Simple and clear
  • ✅ Fast for creation

Disadvantages:

  • ❌ Doesn’t clear the original array
  • ❌ Old references remain on the old array
  • ❌ Can lead to memory leaks

4. Loop with pop()

const items = [1, 2, 3, 4, 5];
while (items.length > 0) {
  items.pop();
}
 
console.log(items); // []

Advantages:

  • ✅ Preserves references
  • ✅ Can process each element

Disadvantages:

  • ❌ Slowest method
  • ❌ Many operations

5. Loop with shift()

const data = ["a", "b", "c"];
while (data.length > 0) {
  data.shift();
}
 
console.log(data); // []

Disadvantages:

  • ❌ Very slow (shift rebuilds indices)
  • ❌ Not recommended to use

Performance comparison

Performance test

function performanceTest() {
  const arraySize = 1000000;
  
  // Test 1: length = 0
  console.time('length = 0');
  let arr1 = new Array(arraySize).fill(1);
  arr1.length = 0;
  console.timeEnd('length = 0');
  
  // Test 2: splice(0)
  console.time('splice(0)');
  let arr2 = new Array(arraySize).fill(1);
  arr2.splice(0);
  console.timeEnd('splice(0)');
  
  // Test 3: new array
  console.time('new array');
  let arr3 = new Array(arraySize).fill(1);
  arr3 = [];
  console.timeEnd('new array');
  
  // Test 4: pop() in loop
  console.time('while pop');
  let arr4 = new Array(arraySize).fill(1);
  while (arr4.length > 0) {
    arr4.pop();
  }
  console.timeEnd('while pop');
}
 
performanceTest();

Results (approximate)

MethodTime (ms)MemoryReferences
length = 0~0.1MinimumPreserves
splice(0)~2-5MediumPreserves
array = []~0.1MediumDoesn’t preserve
while pop()~50-100MaximumPreserves

Practical examples

1. Clearing shopping cart

class ShoppingCart {
  constructor() {
    this.items = [];
  }
  
  addItem(item) {
    this.items.push(item);
  }
  
  // Fast cart clearing
  clear() {
    this.items.length = 0; // Preserve array reference
  }
  
  // Clearing with getting removed elements
  clearAndGetItems() {
    return this.items.splice(0); // Return removed items
  }
}
 
const cart = new ShoppingCart();
cart.addItem({ name: "Bread", price: 30 });
cart.addItem({ name: "Milk", price: 60 });
 
console.log(cart.items.length); // 2
cart.clear();
console.log(cart.items.length); // 0

2. Clearing task list

class TodoManager {
  constructor() {
    this.tasks = [];
    this.observers = []; // Subscribers to changes
  }
  
  addObserver(callback) {
    this.observers.push(callback);
  }
  
  addTask(task) {
    this.tasks.push(task);
    this.notifyObservers();
  }
  
  // Clearing with notifying subscribers
  clearAllTasks() {
    const removedTasks = this.tasks.splice(0); // Get removed
    this.notifyObservers('cleared', removedTasks);
    return removedTasks;
  }
  
  // Fast clearing without notifications
  fastClear() {
    this.tasks.length = 0;
  }
  
  notifyObservers(action = 'updated', data = null) {
    this.observers.forEach(callback => {
      callback(this.tasks, action, data);
    });
  }
}
 
const todoManager = new TodoManager();
 
// Subscribe to changes
todoManager.addObserver((tasks, action, data) => {
  console.log(`Action: ${action}, tasks: ${tasks.length}`);
  if (data) console.log('Removed:', data);
});
 
todoManager.addTask("Learn arrays");
todoManager.addTask("Write code");
todoManager.clearAllTasks(); // Clear with notification

3. Data buffer

class DataBuffer {
  constructor(maxSize = 1000) {
    this.buffer = [];
    this.maxSize = maxSize;
  }
  
  add(data) {
    this.buffer.push(data);
    
    // Clear buffer if size exceeded
    if (this.buffer.length > this.maxSize) {
      this.clear();
    }
  }
  
  // Fast buffer clearing
  clear() {
    this.buffer.length = 0;
    console.log('Buffer cleared');
  }
  
  // Clearing with keeping last N elements
  clearKeepLast(keepCount = 10) {
    if (this.buffer.length > keepCount) {
      const toKeep = this.buffer.slice(-keepCount);
      this.buffer.length = 0;
      this.buffer.push(...toKeep);
    }
  }
  
  getData() {
    return [...this.buffer]; // Return copy
  }
}
 
const buffer = new DataBuffer(5);
buffer.add("data 1");
buffer.add("data 2");
buffer.add("data 3");
buffer.add("data 4");
buffer.add("data 5");
buffer.add("data 6"); // Buffer will clear automatically

Practice tasks

Task 1

const arr = [1, 2, 3];
const ref1 = arr;
const ref2 = arr;
 
arr.length = 0;
 
console.log(arr.length);
console.log(ref1.length);
console.log(ref2.length);
Answer 0, 0, 0 — all references point to one array, so changing length affects all references.

Task 2

let numbers = [1, 2, 3, 4, 5];
const backup = numbers;
 
numbers = [];
 
console.log(numbers.length);
console.log(backup.length);
console.log(backup);
Answer 0, 5, [1, 2, 3, 4, 5] — assigning a new array doesn't affect existing references.

Task 3

const data = ["a", "b", "c", "d"];
const removed = data.splice(0);
 
console.log(data);
console.log(removed);
console.log(data === removed);
Answer [], ["a", "b", "c", "d"], false — splice returns a new array with removed elements.

Modern capabilities

1. Using with destructuring

const items = [1, 2, 3, 4, 5];
 
// Save elements before clearing
const [first, second, ...rest] = items;
items.length = 0;
 
console.log(first, second, rest); // 1, 2, [3, 4, 5]
console.log(items); // []

2. Clearing with Promise

class AsyncDataManager {
  constructor() {
    this.data = [];
  }
  
  async clearAsync() {
    return new Promise((resolve) => {
      // Simulate async clearing
      setTimeout(() => {
        const removedCount = this.data.length;
        this.data.length = 0;
        resolve(removedCount);
      }, 100);
    });
  }
}
 
const manager = new AsyncDataManager();
manager.data.push(1, 2, 3, 4, 5);
 
manager.clearAsync().then(count => {
  console.log(`Removed ${count} elements`);
});

3. Clearing using Proxy

function createClearableArray(initialData = []) {
  const array = [...initialData];
  
  return new Proxy(array, {
    set(target, property, value) {
      if (property === 'clear') {
        target.length = 0;
        return true;
      }
      target[property] = value;
      return true;
    }
  });
}
 
const smartArray = createClearableArray([1, 2, 3, 4, 5]);
console.log(smartArray); // [1, 2, 3, 4, 5]
 
smartArray.clear = true; // Clear trigger
console.log(smartArray); // []

Best practices

✅ Recommendations

// 1. Use length = 0 for fast clearing
const fastClear = (arr) => {
  arr.length = 0; // ✅ Fastest method
};
 
// 2. Use splice(0) when you need removed elements
const clearAndBackup = (arr) => {
  return arr.splice(0); // ✅ Returns removed
};
 
// 3. Document method choice
class DataManager {
  clearData() {
    // Use length = 0 to preserve references
    // and maximum performance
    this.data.length = 0;
  }
}
 
// 4. Check if clearing is necessary
const safeClear = (arr) => {
  if (arr && arr.length > 0) {
    arr.length = 0;
  }
};

❌ What to avoid

// ❌ Slow clearing through shift
while (array.length > 0) {
  array.shift(); // Very slow!
}
 
// ❌ Creating new array when you need to preserve references
function clearArray(arr) {
  arr = []; // Doesn't affect original array!
  return arr;
}
 
// ❌ Clearing in forEach loop
array.forEach((item, index) => {
  delete array[index]; // Creates sparse array
});
 
// ❌ Using delete
for (let i = 0; i < array.length; i++) {
  delete array[i]; // Doesn't change length!
}

Common mistakes

1. Misunderstanding references

// ❌ Problem
function clearUserArray(users) {
  users = []; // Doesn't clear original array!
  return users;
}
 
const myUsers = ["Anna", "Boris"];
const cleared = clearUserArray(myUsers);
console.log(myUsers); // ["Anna", "Boris"] — not cleared!
 
// ✅ Solution
function clearUserArray(users) {
  users.length = 0; // Clears original array
  return users;
}

2. Forgetting about splice return value

// ❌ Data loss
const importantData = ["important", "data"];
importantData.splice(0); // Removed data is lost!
 
// ✅ Saving data
const importantData2 = ["important", "data"];
const backup = importantData2.splice(0); // Save removed
console.log(backup); // ["important", "data"]

3. Clearing during iteration

// ❌ Problem
const numbers = [1, 2, 3, 4, 5];
numbers.forEach((num, index) => {
  if (num > 3) {
    numbers.length = 0; // Interrupts iteration!
  }
});
 
// ✅ Solution
const numbers2 = [1, 2, 3, 4, 5];
const shouldClear = numbers2.some(num => num > 3);
if (shouldClear) {
  numbers2.length = 0;
}

Summary

Clearing an array is an important operation in JavaScript with several approaches:

Main methods:

  • array.length = 0 — fastest, preserves references
  • array.splice(0) — returns removed elements
  • array = [] — creates new array
  • while(array.pop()) — slow, but with control

Method choice depends on:

  • 🚀 Performancelength = 0 is fastest
  • 🔗 References — whether to preserve existing references
  • 📦 Data — whether removed elements are needed
  • 💾 Memory — whether to minimize consumption

Recommendations:

// For most cases
array.length = 0;
 
// When you need removed elements
const removed = array.splice(0);
 
// For creating new array
let array = [];

Understanding the differences between methods is the foundation for efficient array work in JavaScript!


Want more interview preparation articles? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪