How to Remove all Elements from an Array in Javascript?

Sep 16, 2022 . Admin



Hello dev,

oday our leading topic is how to remove all elements from an array in javascript. This article will give you simple example of how to remove all elements of array in javascript. I would like to share with you how do i empty an array in javasrcipt. Here you will learn in javascript how to empty an array. Alright, let’s dive into the steps.

In this tutorial, I am going to explain to you to remove all elements from an array in javascript.This is the fastest way to empty an array to assign the array to a new empty array. It works perfectly if you do not have any references to the original array.

The second way to empty an array is to set its length to zero.to empty an array is to remove all of its elements using the splice() method.the splice() method removed all the elements of an array and returned the removed elements as an array.

So, let's see bellow solution:

Example: 1
index.html
<!DOCTYPE html>
<html>
    <head>
        <title>How to Remove all Elements from an Array in Javascript? - MyWebtuts.com</title>
    </head>
    <body>
        <h1>How to Remove all Elements from an Array in Javascript? -  MyWebtuts.com</h1>
        
        <script type="text/javascript">
            let a = [1,2,3];
            let b = a;
            a = [];

            //Give output to console...
            console.log(a); 
        </script>
    </body>
</html>
Output:
[]
Example: 2 index.html
<!DOCTYPE html>
<html>
    <head>
        <title>How to Remove all Elements from an Array in Javascript? - MyWebtuts.com</title>
    </head>
    <body>
        <h1>How to Remove all Elements from an Array in Javascript? -  MyWebtuts.com</h1>
        
        <script type="text/javascript">
            let a = [1,2,3];
            a.length = 0;
            a.splice(0,a.length);
           
            //Give output to console...;
            console.log(a); 
        </script>
    </body>
</html>
Output:
[]
I hope it will help you...
#Javascript