This section provides a tutorial example on how to access array elements with element indexes.
Array elements can be access with array indexes with several simple rules:
Like many other programming languages,
an array element can be accessed with the array element syntax of array_name[index].
An array index starts with 0.
The length of an array is defined as the highest index of all elements plus 1.
There is no index-out-of-bound exception in JavaScript.
If an index greater than the array length is specified when retrieving an array element,
the "undefined" value will be returned.
If an index greater than the array length is specified when storing an array element,
the array will be expanded to store the element at the specified index.
Here is a tutorial example JavaScript that shows you how to store or retrieve array elements
with element indexes:
<html>
<!-- Access_Array_Elements.html
Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head><title>Access Array Elements</title></head>
<body>
<pre>
<script type="text/javascript">
// Creating an empty array
var glossary = new Array();
// Adding the first element
glossary[0] = "JavaScript";
// Adding the second element at index 10
// This extends the array length to 11
glossary[10] = "Web";
document.write("Element at index of 0: "+glossary[0]+"\n");
document.write("Element at index of 5: "+glossary[5]+"\n");
document.write("Element at index of 10: "+glossary[10]+"\n");
document.write("Element at index of 15: "+glossary[15]+"\n");
</script>
</pre>
</body>
</html>
The output of this sample JavaScript is:
Element at index of 0: JavaScript
Element at index of 5: undefined
Element at index of 10: Web
Element at index of 15: undefined