Arrays In JavaScript

Discussion in 'JavaScript and AJAX' started by Sagar Jaybhay, Dec 31, 2019.

  1. Sagar Jaybhay

    Sagar Jaybhay New Member

    Joined:
    Jan 28, 2019
    Messages:
    29
    Likes Received:
    17
    Trophy Points:
    3
    Gender:
    Male
    Occupation:
    Sr. Software Developer
    Location:
    Pune
    Home Page:
    https://sagarjaybhay.net
    An array is a collection and it is zero-indexed. The meaning of this is the first element is at index zero and the last element is at an index of array length -1 position.

    The array in JavaScript has length property which returns the size of that array.


    Code:
    var array = [];
    console.log("Array Length -- "+ array.length);
    

    upload_2019-12-31_19-32-24.png



    Code:
    var array = new Array(100);
    console.log("Array Length -- "+ array.length);
    


    In this example we only initialize the array and we are not adding any element in array. If you see the output you will see we initialize at 100 and length is also 100.

    upload_2019-12-31_19-32-58.png


    How to retrieve first and last element in array?

    Code:
    var array = [100,200,300]
    console.log("First Element -- " +array[0]);
    console.log("Last Element -- " + array[array.length-1]);
    
    document.write("Array Is " + array+"<br/>");
    
    document.write("First Element -- " + array[0] + "<br/>");
    document.write("Last Element -- " + array[array.length - 1] + "<br/>");
    
    upload_2019-12-31_19-33-35.png


    Different ways to declare array in javascript

    1) Declaring and populating array at the same time
    Code:
    Var array=[10,20,30];
    
    Console.log(array);
    
    2) Declaring array with array constructor: in this method we declare array with array constructor and then populate this array with the index. In javascript the array are not fixed length array type in other languages like c#,java this will grow dynamically even though they will declared with fixed length.
    Code:
    var constructor_array = new Array(2);
    
    constructor_array[0] = 10;
    
    constructor_array[1] = 20;
    
    constructor_array[3] = 30;
    
    console.log(constructor_array);
    
    console.log("Second Array Length - "+constructor_array.length);
    
    
    upload_2019-12-31_19-34-19.png
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice