Accessing Array Elements

By: Dusty Arlia
Published on September 11, 2012
Last Updated on Friday, July 03, 2015 at 3:28 PM
Total Updates: 3

Since arrays hold many values you can't simply reference it by name to access one of its elements. A unique number called an index refers to the position of each element in an array. Use the index number to access a particular element. The first position in an array is always referred to as index 0. Here's an example of an array:

var fullNames = ['Dusty Arlia',
                 'Justin Bieber',
                 'Emma Watson',
                 'Kim Kardashian',
                 'Kanye West',

In this example, an alert box opens with "Dusty Arlia" written inside it. This shows that arrays are zero-indexed. Zero-indexed means that the first element in an array has an index value of 0. The second element in an array has an index value of 1. To calculate the index value, just subtract one from the element's position number. Here's how you can access each element in the array above:

Element Value Index Number Access Element by Using...
Dusty Arlia 0 fullNames[0]
Justin Bieber 1 fullNames[1]
Emma Watson 2 fullNames[2]
Kim Kardashian 3 fullNames[3]
Kanye West 4 fullNames[4]

Change the value of an array element like this:

fullNames[4] = 'Lady Gaga';

When you use the index number to access an array element you are using a literal number. You will see the index number in between two square brackets ([#]). There is two other ways to access an array element. You can replace the index number with a variable or you can replace the index number with an equation. Here is an example of using a variable instead of an index number:

var i = 0;

And here's an example of using an equation:

var i = 0
alert(fullNames[i + 1]);

Or here's another equation:

alert(fullNames[fullNames.length - 1])