Skip to content

WebDevHubs

  • Home
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • Java
  • Selenium
  • PHP
  • Python
  • Programs
  • 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 *

Categories

  • CSS
  • HTML
  • Interview Experience
  • Java
  • JavaScript
  • Lodash
  • PHP
  • Programs
  • Python
  • Selenium
  • Software Testing
  • Web Technologies
  • Web Templates

Recent Posts

  • Java ArrayList trimToSize() Method
  • Java ArrayList toArray() Method
  • Java ArrayList subList() Method
  • Java ArrayList spliterator() Method
  • Java ArrayList sort() Method

Recent Comments

No comments to show.

Important Pages

  • About Us
  • Contact Us
  • Terms of Use
  • Privacy Policy

Web Development

  • HTML
  • CSS
  • JavaScript
  • PHP

Programming Languages

  • Java
  • Python
  • PHP
  • Programs

Others

  • Selenium
  • Lodash
  • Java ArrayList
  • JavaScript Array Methods

Copyright © 2025 WebDevHubs.

Powered by PressBook Green WordPress theme