Change Array Elements

You refer to an array element by referring to the index number. This statement accesses the value of the first element in cars:

  var name = cars[0];

This statement modifies the first element in cars:

  cars[0] = "Opel";

HTML file: Displayed by browser:
<body>
<h4>The original value for [0] is:</h4>
<p id="original"></p>
<h4>The modified value for [0] is:</h4>
<p id="modified"></p>
<script>
var cars = [
    "Saab",
    "Volvo",
    "BMW",
    "Camaro",
    "Fiero",
    "Corvette",
    "Firebird"
];
document.getElementById("original").innerHTML = cars[0];
cars[0] = "Opel";
document.getElementById("modified").innerHTML = cars[0];
</script>
</body>

The original value for [0] is:

The modified value for [0] is:

Array indexes start with 0, so the first element in an array is [0] while the second is [1].

BackTable of ContentsNext