Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Get the first and last item in an array using JavaScript?
JavaScript arrays are 0-indexed, meaning the first element is at position 0 and the last element is at position length - 1. Here are several ways to access the first and last elements of an array.
Using Index Access
The most straightforward method uses bracket notation with index positions:
let arr = [1, 'test', {}, 'hello', 42];
// First element
console.log("First element:", arr[0]);
// Last element
console.log("Last element:", arr[arr.length - 1]);
First element: 1 Last element: 42
Using Array Methods
JavaScript provides built-in methods for accessing array elements:
let fruits = ['apple', 'banana', 'orange', 'mango'];
// Using at() method (ES2022)
console.log("First:", fruits.at(0));
console.log("Last:", fruits.at(-1));
// Using slice() method
console.log("First with slice:", fruits.slice(0, 1)[0]);
console.log("Last with slice:", fruits.slice(-1)[0]);
First: apple Last: mango First with slice: apple Last with slice: mango
Handling Empty Arrays
Always check for empty arrays to avoid unexpected results:
let emptyArray = [];
let numbers = [10, 20, 30];
function getFirstAndLast(arr) {
if (arr.length === 0) {
return { first: undefined, last: undefined };
}
return {
first: arr[0],
last: arr[arr.length - 1]
};
}
console.log("Empty array:", getFirstAndLast(emptyArray));
console.log("Numbers array:", getFirstAndLast(numbers));
Empty array: { first: undefined, last: undefined }
Numbers array: { first: 10, last: 30 }
Comparison of Methods
| Method | First Element | Last Element | Browser Support |
|---|---|---|---|
| Index Access | arr[0] |
arr[arr.length - 1] |
All browsers |
| at() Method | arr.at(0) |
arr.at(-1) |
ES2022+ (modern browsers) |
| slice() Method | arr.slice(0, 1)[0] |
arr.slice(-1)[0] |
All browsers |
Conclusion
Index access (arr[0] and arr[arr.length - 1]) is the most common and widely supported method. The at() method offers cleaner syntax for modern environments, especially for accessing the last element with negative indexing.
Advertisements
