JavaScript Array Object
In this JavaScript tutorial, you will learn about JavaScript Array Object, its properties and methods.
Usage of the Array Object:
The Array object is used to store a set of values in a single variable name.
There are many operations involved with Array object:
- Defining Array object
- Adding Values to Array
- Accessing Array
- Editing or Modifying the Values of an Array
These topics have been addressed in previous sections on Arrays in JavaScript.
In this section, the properties and methods of Array Object in JavaScript will be outlined.
Properties of array Object:
length:
The length property of an array object returns the number of elements in an array.
General Syntax of length property of an array Object in JavaScript:
arrayObject.length
For example:
<body> document.write("Old value of length:" + arr.length)
<html>
<script type="text/javascript">
var exforsys = new Array(2)
exforsys[0] = "Good"
exforsys[1] = "Best"
document.write("<br />")
arr.length=4
document.write("Modified value of length:"+arr.length)
</script>
</body>
</html>
The output of the code above will be:
Old value of length: 2
Modified value of length: 4
index Property :
The index Property is a read-only property and this gives the index of the Array Object.
Methods of Array Object in JavaScript:
There are various methods used with Array object of JavaScript:
- valueOf()
- sort()
- concat()
- join()
- pop()
- push()
- shift()
- reverse()
- slice()
- splice()
- toString()
- unshift()
valueOf():
The method valueOf() of the Array object of JavaScript is used to return the primitive value of an Array object.
NOTE: the valueOf() method of the Array object is usually called automatically by JavaScript and not explicitly by the programmer.
General syntax of the valueOf() method of the Array object of JavaScript:
arrayObject.valueOf()
sort():
The method sort()is used to sort the elements of an array object in JavaScript.
General syntax of the sort() method of the Array object of JavaScript:
arrayObject.sort(sortby)
In the above, the sortby argument is optional. If it is given, it indicates the order in which the sorting must take place which must be defined as a function.
For example:
<body>
<html>
<script type="text/javascript">
var exforsys = new Array(5)
exforsys[0] = "Test"
exforsys[1] = "Welcome"
exforsys[2] = "Training"
exforsys[3] = "Good"
exforsys[4] = "Day"
document.write("The Original Array is:" +"<br />")
document.write(exforsys + "<br />")
document.write("The Sorted Array is:" +"<br />")
document.write(exforsys.sort())
</script>
</body>
</html>
The output of the above example is:
The Original Array is:
Test,Welcome,Training,Good,Day
The Sorted Array is:
Day,Good,Test,Training,Welcome
The first output statement prints the array as such without sorting. The second document.write statement has sort() method defined in it with the Array Object exforsys. Thus, the array is sorted before printing.