Member-only story
In JavaScript, you can access elements in an array using their index. The index is a numeric value that represents the position of an element within the array. In this tutorial, we’ll explore how to access elements in an array in JavaScript with some examples.
Not a Medium member? Read this article here
Accessing Elements in an Array by Index
To access an element in an array, you can use square brackets ([]
) with the index of the element you want to access. The index starts at 0 for the first element in the array and increments by 1 for each subsequent element.
Here’s an example of how to access elements in an array in JavaScript:
const fruits = ['apple', 'banana', 'orange', 'grape'];
// Access the first element
const firstFruit = fruits[0];
console.log(firstFruit); // Output: "apple"
// Access the third element
const thirdFruit = fruits[2];
console.log(thirdFruit); // Output: "orange"
In this example, we have an array of fruits and we use square brackets with the index of the element we want to access to assign the value of the first and third elements to variables.
Accessing Elements in an Array with Loops