Define Array in JavaScript

Introduction

In this article we will learn about various ways to define arrays in JavaScript. JavaScript arrays are used to store multiple values in a single variable.

Let's look at the following snippets.

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

</head>

<body>

    <form id="form1" runat="server">

    <script>  

                    var arr = ['x', 'y', 'z']; 1

        alert(arr[0]);  

    </script>

    </form>

</body>

</html> 

Here we have defined an array using the “var” keyword. Then we are accessing the element of the array at index 0.

var keyword 
 
Now we will use an Array() function to create an array.
 

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

</head>

<body>

    <form id="form1" runat="server">

    <script>  

        var arr = new Array("Ramesh", "Suresh", "Hareesh");

        alert(arr[0]);  

    </script>

    </form>

</body>

</html> 

 
Array function 

In the following snippet, we are not creating an element at the time of Array () creation.

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

</head>

<body>

    <form id="form1" runat="server">

    <script>  

                    var arr = new Array();

        arr[0] = 100;

        arr[1] = "Rama";

        arr[2] = "sagar";

        alert(arr[1] + arr[2]);  

    </script>

    </form>

</body>

</html> 

 
creating element in time of Array creation 

Summary

In this article we learned various various ways to define arrays in JavaScript. In future articles we will learn some more basic concepts of JavaScript.

Up Next
    Ebook Download
    View all
    Learn
    View all