Displaying Arrays

JavaScript arrays are used to store multiple values in a single variable. Keep in mind that spaces and line breaks are not important and that declaration can span multiple lines. The values for each item in the array list are zero-based. On this page, the values of the first variable, "cars", are Saab=0, Volvo=1, BMW=2 while the values of the second variable, "sportcars", are Camaro=0, Fiero=1, Corvette=2 and Firebird=3.

In this example, we create two arrays, and assign values to them, via a script. With this script, the first line creates the array for the variable "cars". The second line finds the element with id="democars", and displays the [0] array in the "innerHTML" of it. The third line of the script creates the array for the variable "sportcars" which is spread out over six lines. Finally on the last line, the script will find the element with id="sportycars", and display the [2] array.

HTML file: Displayed by browser:
<body>
<p id="democars">InnerHTML</p>
<p id="sportycars">InnerHTML</p>
<script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("democars").innerHTML = cars[0];
var sportcars = [
    "Camaro",
    "Fiero",
    "Corvette",
    "Firebird"
];
document.getElementById("sportycars").innerHTML = sportcars[2];
</script>
</body>

InnerHTML

InnerHTML

Never put a comma after the last element (like "BMW", or "Firebird",). The effect is inconsistent across browsers.

BackTable of ContentsNext