How to empty an array in JavaScript?
There are many ways to empty an array in JavaScript some of them are discussed below:
Method 1: Setting to new Array: This method sets the array variable to new array of size zero, then it will work perfectly.
Example:
<!DOCTYPE html> < html > < head > < title > JavaScript to set array empty </ title > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "up" ></ p > < button onclick = "empty()" > Click to Empty </ button > < p id = "down" style = "color: green" ></ p > <!-- Script to set size of array to zero --> < script > var GFG_Array = [1, 2, 3, 4, 5]; var up = document.getElementById("up"); up.innerHTML = GFG_Array; var down = document.getElementById("down"); down.innerHTML = "length of GFG_Array = " + GFG_Array.length; function empty() { GFG_Array = []; down = document.getElementById("down"); down.innerHTML = "length of GFG_Array = " + GFG_Array.length; } </ script > </ body > </ html > |
Output:
- Before clicking the button:
- After clicking the button:
Method 2: Using length property: This method sets the length of array to zero.
Example:
<!DOCTYPE html> < html > < head > < title > Create empty array </ title > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "up" ></ p > < button onclick = "empty()" > Click to Empty </ button > < p id = "down" style = "color: green" ></ p > <!-- Script to set the size of array to zero --> < script > var GFG_Array = [1, 2, 3, 4, 5]; var up = document.getElementById("up"); up.innerHTML = GFG_Array; var down = document.getElementById("down"); down.innerHTML = "length of GFG_Array = " + GFG_Array.length; function empty() { GFG_Array.length = 0; down = document.getElementById("down"); down.innerHTML = "length of GFG_Array = " + GFG_Array.length; } </ script > </ body > </ html > |
Output:
- Before clicking the button:
- After clicking the button:
Method 3: Using pop method: This method pop the array element continuously and get the empty array. But this method takes more time than others and not much preferred.
Example:
<!DOCTYPE html> < html > < head > < title > Create empty array </ title > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "up" ></ p > < button onclick = "empty()" > Click to Empty </ button > < p id = "down" style = "color: green" ></ p > <!-- Script to set the size of array to zero --> < script > var GFG_Array = [1, 2, 3, 4, 5]; var up = document.getElementById("up"); up.innerHTML = GFG_Array; var down = document.getElementById("down"); down.innerHTML = "length of GFG_Array = " + GFG_Array.length; function empty() { while(GFG_Array.length > 0) { GFG_Array.pop(); } down = document.getElementById("down"); down.innerHTML = "length of GFG_Array = " + GFG_Array.length; } </ script > </ body > </ html > |
Output:
- Before clicking the button:
- After clicking the button: