Object Array

An array with objects of user defined class type is called Object Array.

Example

In the following example, we initialize an Array with objects fruit1, fruit2, and fruit3 of user defined class type Fruit, and access its elements using index.

index.html

<!doctype html>
<html>
  <body>
    <h2>JavaScript - Object Array</h2>
    <pre id="output"></pre>

    <script>
      class Fruit {
        constructor(name, quantity) {
          this.name = name;
          this.quantity = quantity;
        }
        toString() {
          return this.name + '-' + this.quantity;  
        }
      }
      
      var fruit1 = new Fruit('apple', 26);
      var fruit2 = new Fruit('banana', 14);
      var fruit3 = new Fruit('cherry', 47);

      var fruits = [fruit1, fruit2, fruit3];

      document.getElementById("output").innerHTML = fruits;
      document.getElementById("output").innerHTML += "fruits[1] name: " + fruits[1].name;
    </script>

  </body>
</html>