JavaScript Array Properties

The properties of Array objects are as follows :

1. constructor :

The JavaScript constructor property returns the constructor function for an object. The return value is a reference to the function, not the name of the function. Lets see an example :
<!DOCTYPE html>
<html>
<body>
  <script>
    var names = ["John", "Kumar", "Jack", "Tom"];
    document.write(names.constructor);
  </script>
</body>
</html>
Output :


In JavaScript the constructor property for Array is "function Array() { [native code] }", and for numbers is "function Number() { [native code] }", and for strings is "function String() { [native code] }".

Example :
<script>
  var names = ["John", "Kumar", "Jack", "Tom"];
  document.write(names.constructor + "<br/>");
  
  var num = 2000;
  document.write(num.constructor + "<br/>");
  
  var str = "This is test string.";
  document.write(str.constructor + "<br/>");
</script>
Output :


2. length :

The length property of an array returns the length or the number of elements of an array. the syntax of length property is as follows :
  array.length;
Lets see an example :
<!DOCTYPE html>
<html>
<body>
  <script>
    var myarray = [100, 200, 300, 546, 970];
    document.write("Length of Array is : " + myarray.length);
  </script>
</body>
</html>
Output :


With the help of length property its easy to use for loop to extract element from array, where in for loop we can use length property in condition statement. for example :
<!DOCTYPE html>
<html>
<body>
  <script>
    var names = ["John", "Kumar", "Jack", "Tom"];

    for(var x = 0; x < names.length; x++) {
      document.write(names[x] + "<br/>");
    }
  </script>
</body>
</html>
Output :


3. Prototype :

The prototype property allows you to add properties and methods to an object. Prototype is a global property which is available with almost all the objects. When constructing a property or method, ALL arrays will be given the property, and its value, as default. The basic syntax of prototype property is :
  Array.prototype.name = value
For example the below code construct new method named Ucase which convert all the array elements to uppercase :
<!DOCTYPE html>
<html>
<body>
  <script>
    Array.prototype.Ucase = function() {
      var i;
      for (i = 0; i < this.length; i++) {
        this[i] = this[i].toUpperCase();
      }
    };

    var names = ["John", "Kumar", "Jack", "Tom"];
    names.Ucase();

    for(var x = 0; x < names.length; x++) {
      document.write(names[x] + "<br/>");
    }
  </script>
</body>
</html>
Output :


Next Topic :