Get the First Item in an Array in JavaScript
In JavaScript, arrays are used to store multiple values in a single variable. Whether it's a list of fruits, names, or even tasks to do, arrays help organize information. But what if you only need the first item? In this tutorial, we will walk you through several ways to get the first item in an array with examples and explanations.
Method 1: Using Index 0
JavaScript arrays are zero-indexed, meaning the first element is always at index 0
. This is the most straightforward and recommended method to retrieve the first item.
const fruits = ["apple", "banana", "cherry"];
const firstFruit = fruits[0];
console.log("First fruit:", firstFruit);
First fruit: apple
Method 2: Using array.at(0)
The at()
method is a newer and safer way to access elements by index. It's especially useful when you want to use negative indices to count from the end of the array. For the first item, you simply use .at(0)
.
const fruits = ["apple", "banana", "cherry"];
const first = fruits.at(0);
console.log("First item using at():", first);
First item using at(): apple
Method 3: Using Array Destructuring
Destructuring is a clean and modern JavaScript feature that lets you unpack values from arrays (or objects) into distinct variables. This method improves readability, especially when pulling the first item and ignoring the rest.
const fruits = ["apple", "banana", "cherry"];
const [firstItem] = fruits;
console.log("First item using destructuring:", firstItem);
First item using destructuring: apple
When Should You Use Each Method?
- Use
array[0]
: When you want a quick and clear way to get the first item. It’s fast, readable, and widely used. - Use
array.at(0)
: When you prefer consistency with negative indexing or want a method-based approach. - Use Destructuring: When you are unpacking multiple values or writing modern, declarative code. It shines in React, Node.js, and ES6-heavy projects.
Comments
Loading comments...