Monday, July 15, 2024
HomeLanguagesJavascriptHow to empty an array in JavaScript ?

How to empty an array in JavaScript ?

There are many ways to empty an array using JavaScript. In this article, we will discuss and execute the top three ways to make an array empty.

  1. Setting the array to a new array.
  2. By using the length property to set the array length to zero.
  3. By using the pop() method we will be popping each element of the array.

Below examples will illustrate the above-mentioned ways to empty an array.

Example 1: Setting to a new Array means setting the array variable to a new array of size zero, then it will work perfectly. 

Javascript




let Arr = [1, 2, 3, 4, 5];
 
console.log("Array Elements: " + Arr);
console.log("Array Length: " + Arr.length);
 
function emptyArray() {
    Arr = [];
    console.log("Empty Array Elements: " + Arr);
    console.log("Empty Array Length: " + Arr.length);
}
 
emptyArray();


Output

Array Elements: 1,2,3,4,5
Array Length: 5
Empty Array Elements: 
Empty Array Length: 0

Example 2: By using the length property, we set the length of the array to zero which will make the array an empty array.

Javascript




let Arr = [1, 2, 3, 4, 5];
 
console.log("Array Elements: " + Arr);
console.log("Array Length: " + Arr.length);
 
function emptyArray() {
    Arr.length = 0;
    console.log("Empty Array Elements: " + Arr);
    console.log("Empty Array Length: " + Arr.length);
}
 
emptyArray();


Output

Array Elements: 1,2,3,4,5
Array Length: 5
Empty Array Elements: 
Empty Array Length: 0

Example 3: By using pop() method on each element of the array, we pop up the array element continuously and get an empty array. But this method takes more time than others and is not much preferred. 

Javascript




let Arr = [1, 2, 3, 4, 5];
 
console.log("Array Elements: " + Arr);
console.log("Array Length: " + Arr.length);
 
function emptyArray() {
    while (Arr.length > 0) {
        Arr.pop();
    }
 
    console.log("Empty Array Elements: " + Arr);
    console.log("Empty Array Length: " + Arr.length);
}
 
emptyArray();


Output

Array Elements: 1,2,3,4,5
Array Length: 5
Empty Array Elements: 
Empty Array Length: 0

Nango Kalahttps://www.kala.co.za
Experienced Support Engineer with a demonstrated history of working in the information technology and services industry. Skilled in Microsoft Excel, Customer Service, Microsoft Word, Technical Support, and Microsoft Office. Strong information technology professional with a Microsoft Certificate Solutions Expert (Privet Cloud) focused in Information Technology from Broadband Collage Of Technology.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments