This article will show you how to access an array item by its index in JavaScript. Here are several approaches to access an array item by its index in JavaScript, each with a description and complete code example are given below:
1. Using Bracket Notation
Accessing an array item using square bracket notation with the index.
const array = ['Apple', 'Banana', 'Orange']; const index = 1; const selectedItem = array[index]; // Output: Banana console.log(selectedItem);
2. Using Array Destructuring
Using array destructuring to directly extract the value at a specific index.
const array = ['Apple', 'Banana', 'Orange']; const index = 1; const [selectedItem] = array.slice(index, index + 1); // Output: Banana console.log(selectedItem);
3. Using Object Destructuring
Using object destructuring to extract the value at a specific index.
const array = ['Apple', 'Banana', 'Orange']; const index = 1; const { [index]: selectedItem } = array; // Output: Banana console.log(selectedItem);
4. Using Array.find() Method
Using the find()
method to find an element based on a condition (index) in the array.
const array = ['Apple', 'Banana', 'Orange']; const index = 1; const selectedItem = array.find((_, i) => i === index); // Output: Banana console.log(selectedItem);
5. Using Array.at() Method
Using the at()
method to directly access an element at a specified index.
const array = ['Apple', 'Banana', 'Orange']; const index = 1; const selectedItem = array.at(index); // Output: Banana console.log(selectedItem);
6. Using Ternary Operator
Using a ternary operator to conditionally access an array item based on an index.
const array = ['Apple', 'Banana', 'Orange']; const index = 1; const selectedItem = array[index] !== undefined ? array[index] : 'Index out of bounds'; // Output: Banana console.log(selectedItem);
7. Using Optional Chaining
Using optional chaining to access an array item safely, avoiding errors if the index is out of bounds.
const array = ['Apple', 'Banana', 'Orange']; const index = 1; const selectedItem = array[index]?.toUpperCase(); // Output: BANANA console.log(selectedItem);
8. Using a Function
Creating a function to encapsulate the logic of accessing an array item by index.
function getItemByIndex(arr, index) { return arr[index]; } const array = ['Apple', 'Banana', 'Orange']; const index = 1; const selectedItem = getItemByIndex(array, index); // Output: Banana console.log(selectedItem);