When working with arrays, you often need to access individual elements within the array. In JavaScript, you can access array elements using indexing.
Array indexing starts at 0, so the first element of an array is at index 0, the second element is at index 1, and so on. To access an element, you can use square brackets []
after the array name, specifying the index of the element you want to access.
For example, suppose we have an array fruits
that contains three elements: 'apple', 'banana', and 'orange'. We can access the first element using fruits[0]
, which will return 'apple'. Similarly, we can access the last element using fruits[2]
, which will return 'orange'.
Here's an example:
xxxxxxxxxx
const fruits = ['apple', 'banana', 'orange'];
console.log(fruits[0]); // Output: apple
console.log(fruits[2]); // Output: orange
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment