Blog

Arrays in JavaScript

An Array in JavaScript is a collection of items. The items can be accessed and modified. The whole array can be passed as a parameter to some function. Since JavaScript is typeless we can store data of any kind. The array automatically creates a variable called length which automatically gives the size of the array. The length is supposed to be readonly. However I’ve tried assigning  to it(in Chrome) and actually changes the length of the array. The newly added positions will have the value undefined.
Declaring Arrays:

  1. var x=new Array();
    Creates a new Array with zero elements. New Elements can always be added

    var items=new Array();
    items[0]=”Popat”;
    items[1]=10;
    items[2]=Math;
    items[3]=Math.sqrt;
    To print this array we can use the following loop:
    var output = “”;
    for (var i = 0; i <= items.length – 1; i++)
    output = output + “,” + items[i];
    document.getElementById(“d”).innerHTML = output;,Popat,10,[object Math],function sqrt() { [native code] }

  2. var x=new Array(list of elements);

    function f() {
    var items = new Array(‘Popat’,10,Math,Math.sqrt);
    var output = “”;
    for (var i = 0; i <= items.length – 1; i++)
    output = output + “,” + items[i];
    document.getElementById(“d”).innerHTML = output;
    }
    ,Popat,10,[object Math],function sqrt() { [native code] }

  3. A simpler syntax is: a=[list of items]

    function f() {
    var items = [‘Popat’,10,Math,Math.sqrt];
    var output = “”;
    for (var i = 0; i <= items.length – 1; i++)
    output = output + “,” + items[i];
    document.getElementById(“d”).innerHTML = output;
    }
    ,Popat,10,[object Math],function sqrt() { [native code] }

    In the next post we will study methods of the Array object.

Leave a Reply

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