Each element in an array has a numbered position known as its index. We can access individual items using their index, which is similar to referencing an item in a list based on the item’s position.
0 rather than
1. Therefore, the first item in an array will be at position
0. Let’s see how we could access an element in an array:
In the code snippet above:
citiesis an array that has three elements.
with the index after the name of the array to access the element.
citieswill access the element at index
0in the array
cities. You can think of
citiesas accessing the space in memory that holds the string
You can also access individual characters in a string using bracket notation and the index. For instance, you can write:
const hello = 'Hello World'; console.log(hello); // Output: W
The console will display
W since it is the character that is at index
Individual elements in arrays can also be stored to variables.
Create a variable named
listItem and set it equal to the first item in the
famousSayings array using square bracket notation (
console.log() to print the
listItem variable to the console.
console.log() the third element in the
famousSayings array using bracket notation to access the element.
Do not save the element to a new variable before you log it.
Awesome, you can access each element in an array using the index. But what happens if you try to access an index that is beyond the last element?
Try to log the item at index
famousSayings to the console. What is logged to the console?