Skip to content

WebDevHubs

  • Home
  • HTML
  • CSS
  • JavaScript
  • Web Technologies
  • Web Templates
  • Toggle search form

How Do I Empty an Array in JavaScript?

Posted on December 18, 2024 By Admin No Comments on How Do I Empty an Array in JavaScript?

There are various methods to empty an array in JavaScript.

1. Setting the Length Property to 0

The length property of an array defines the number of elements in the array. Setting it to 0 effectively clears all elements.

let arr = [10, 20, 30, 40, 50];
arr.length = 0; // Clears the array
console.log(arr); // Output: []

2. Reassigning to an Empty Array

You can replace the existing array with a new empty array using assignment.

let arr = [10, 20, 30, 40, 50];
arr = []; // Reassigns the array
console.log(arr); // Output: []

Note: The original array reference remains unchanged, but other references pointing to the old array will not reflect the update.

3. Using splice() Method

The splice() method can remove all elements of the array by starting at index 0 and removing its entire length.

let arr = [10, 20, 30, 40];
arr.splice(0, arr.length); // Clears the array
console.log(arr); // Output: []

4. Using pop() in a Loop

You can repeatedly use the pop() method to remove elements from the end of the array until it becomes empty.

let arr = [10, 20, 30, 40, 50];

while (arr.length > 0) {
    arr.pop();
}
console.log(arr); // Output: []

5. Using shift() in a Loop

Similar to pop(), you can use shift() to remove elements from the beginning of the array until it’s empty.

let arr = [10, 20, 30, 40, 50];

while (arr.length > 0) {
    arr.shift();
}

console.log(arr); // Output: []
JavaScript, Web Technologies Tags:JavaScript-Array, JavaScript-Questions

Post navigation

Previous Post: Add New Elements at the Beginning of an Array in JavaScript
Next Post: Can We Use a break in forEach JavaScript?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Archives

  • June 2025
  • May 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024

Categories

  • CSS
  • HTML
  • JavaScript
  • Lodash
  • PHP
  • Python
  • Web Technologies
  • Web Templates

Recent Posts

  • JavaScript Array isArray() Method
  • JavaScript Array forEach() Method
  • JavaScript Array includes() Method
  • JavaScript Array keys() Method
  • JavaScript Array lastIndexOf() Method

Recent Comments

No comments to show.

Copyright © 2025 WebDevHubs.

Powered by PressBook Green WordPress theme