You access an array element by referring to the index number.
This statement accesses the value of the first element in cars
:
var name = cars[0];
Example
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];
document.getElementById("demo").innerHTML = cars[0];
Note: Array indexes start with 0.
[0] is the first element. [1] is the second element.
Changing an Array Element
This statement changes the value of the first element in cars
:
cars[0] = "Opel";
Example
var cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
document.getElementById("demo").innerHTML = cars[0];
cars[0] = "Opel";
document.getElementById("demo").innerHTML = cars[0];
Access the Full Array
With JavaScript, the full array can be accessed by referring to the array name:
Example
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
document.getElementById("demo").innerHTML = cars;
Accessing the First Array Element
Example
fruits = ["Banana", "Orange", "Apple", "Mango"];
var first = fruits[0];
var first = fruits[0];
Accessing the Last Array Element
Example
fruits = ["Banana", "Orange", "Apple", "Mango"];
var last = fruits[fruits.length - 1];
var last = fruits[fruits.length - 1];
Practice Excercise Practice now