Learn
Arrays
Accessing Elements
One of the fundamental operations when working with arrays is accessing its elements. By accessing elements, we can retrieve values, perform operations on them, or manipulate the array itself.
To access an element in an array, we use square brackets []
following the array name, along with the index of the element we want to retrieve. The index represents the position of an element within the array, starting from 0 for the first element.
Example
In the example above, we created an array called fruits
with three elements: "apple", "banana", and "orange". We accessed and printed the elements using their indexes: fruits[0]
for the first element, fruits[1]
for the second element, and fruits[2]
for the third element.
Limit of the array element index
It's important to note that if we try to access an element using an index that is out of bounds (i.e., greater than or equal to the array length), we will get undefined
as the result.
Keep in mind that JavaScript arrays are zero-indexed, meaning the first element has an index of 0, the second element has an index of 1, and so on. Understanding this concept is crucial when working with arrays.
Instructions
Declare a variable firstFruit
and assign it the value of the first element in the fruits
array.
Declare a variable lastFruit
and assign it the value of the last element in the fruits
array.
Declare a variable thirdFruit
and assign it the value of the third element in the fruits
array.
Sign up to start coding
Already have an account?
Sign In