Access an Item by Its Position in JavaScript
In JavaScript, arrays let you store and organize multiple values in a single variable. But what makes them truly useful is the ability to access specific items based on their position. In this tutorial, we will show you how to grab any item from a JavaScript array using different techniques — with examples and detailed explanation.
Method 1: Using Bracket Notation with Index
This is the most direct and widely used method for accessing items in an array. JavaScript arrays are zero-based, meaning the first item is at index 0
, the second at 1
, and so on. Simply use brackets and the index number to retrieve the value.
const fruits = ["apple", "banana", "cherry"];
console.log("First fruit:", fruits[0]);
console.log("Second fruit:", fruits[1]);
First fruit: apple
Second fruit: banana
Method 2: Using the at()
Method
Modern JavaScript (ES2022+) introduces the at()
method, which can retrieve elements by index — and even count backwards from the end using negative numbers. This is helpful for both clarity and flexibility.
const fruits = ["apple", "banana", "cherry"];
console.log("Item at index 1:", fruits.at(1));
console.log("Last item using at():", fruits.at(-1));
Item at index 1: banana
Last item using at(): cherry
Method 3: Accessing Items Dynamically with a Variable
Instead of hardcoding the index, you can also use a variable. This is especially useful when the position is calculated based on conditions, user input, or loops.
const fruits = ["apple", "banana", "cherry"];
let position = 2;
console.log("Item at position", position, "is", fruits[position]);
Item at position 2 is cherry
When Should You Use Each Method?
- Bracket notation is perfect for most situations — it’s fast, clear, and readable.
- The
at()
method is ideal when you want to use negative indexing or prefer method chaining for readability. - Using variables is crucial when working in loops, calculations, or user-defined logic.
Comments
Loading comments...