Loading
Array in javascript-tutorial
In JavaScript, an array is a special data structure used to store multiple values in a single variable.
Arrays help organize related data and make it easy to manage lists, collections, and dynamic data.



Ways to Create an Array in JavaScript

JavaScript offers three main ways to create arrays

  • Array Literal Notation
  • Using the new keyword directly
  • Using Array Constructor with new keyword



Array Literal Notation

This is the simples and most common way to create an array.



Syntax:

var arrayName = [value1, value2, ..., valueN];



Example:

<!DOCTYPE html>
<html>

<body>
    <script>
        var emp = ["Praveen", "Prashanth", "Sagar"];
        for (var i = 0; i < emp.length; i++) {
            document.write(emp[i] + "<br/>");
        }
    </script>
</body>

</html>

Output

Uploaded Image




Array Directly (using new keyword)

You can create an array instance using the new keyword.



Syntax:

var arrayName = new Array();



Example:

<!DOCTYPE html>
<html>

<body>
    <script>
        var emp = new Array();
        emp[0] = "Arun";
        emp[1] = "Varun";
        emp[2] = "John";

        for (var i = 0; i < emp.length; i++) {
            document.write(emp[i] + "<br/>");
        }
    </script>
</body>

</html>

Output

Uploaded Image




Array Constructor (using new keyword)

You can also pass elements as arguments to the constructor.



Syntax:

var arrayName = new Array(value1, value2, ..., valueN);



Example:

<!DOCTYPE html>
<html>

<body>
    <script>
        var emp = new Array("Jai", "Vijay", "Smith");
        for (var i = 0; i < emp.length; i++) {
            document.write(emp[i] + "<br/>");
        }
    </script>
</body>

</html>

Output

Uploaded Image



Tip: Arrays in JavaScript can hold mixed data types like numbers, strings, objects, and even other arrays, making them very flexible.