Learn Javascript Dynamic Array Syntax And Declaration – Do not know the Array Size or Array Length

In most of the times during logic building we can not mention or specify the array with a fixed size or length because we don’t know the Array Size or Length at all. In such cases we need Javascript Dynamic Array. Javascript provides us the opportunity to create or declare an array with out mentioning the length. This array will dynamically set its value when a new variable or entry is added.

Declaration Syntax:

var thearrayname= new Array();

Assigning Values:

    thearrayname[0] = "White";
    thearrayname[1] = "Red";
    thearrayname[2] = "Green";
    thearrayname[3] = "Yellow";
    thearrayname[5] = "Purple";

Note: You can add any number of elements as you want. If you missed any index in between length you will get “undefined”. But you can continue the loop till to end.

Complete Javascript Dynamic Array Code Example:

<script type="text/javascript">
    var thearrayname = new Array();

    thearrayname[0] = "White";
    thearrayname[1] = "Red";
    thearrayname[2] = "Green";
    thearrayname[3] = "Yellow";
    thearrayname[5] = "Purple";

    for (i = 0; i < thearrayname.length; i++) {
        document.write("My favourite color " + eval(i + 1) + " is : " + thearrayname[i] + "<br/>");
    }
</script>

Note: Since we don’t know the length we can loop through the array by using the array length function (here thearrayname.length). Another important thing is in the above code we did not assign any value to the index 4. See the impact from below.

Output:
Javascript_Dynamic_Array_Example_Code_Syntax

Download Code Example Javascript Dynamic Array

Posted in Client, Javascript

Leave a Reply

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

     

*