Loading

Arrays

  • In JavaScript, an array is a data structure that allows you to store a collection of values (which can be of any data type) in a single variable.
  • Arrays are commonly used to group related data or elements together.

Ways to construct Array:

  • Array literal notation
  • Array directly (new keyword)
  • Array Constructor (using the new keyword)

Array literal notation

  • It is the simplest way to create an array.
  • Define an array by enclosing a comma-separated list of values in square brackets [].

Syntax:

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

Example:

<html>

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

</html>

Output:

Praveen

Prashanth

Sagar


Array directly (new keyword)

Syntax:

var arrayname=new Array();  
  • new keyword is used to create an instance of an array.

Example:

<html>

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

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

</html>

Output:

Arun
Varun
John


Array Constructor (using the new keyword)

  • You can use the Array constructor to create an array. You can pass elements as arguments to the constructor.

Syntax:

<html>

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

</html>

Output:

Jai
Vijay
Smith