How to get the first element of an array in JavaScript
Accessing the first element of arrays is fundamental for processing data sequences, implementing queue operations, and retrieving initial values in JavaScript applications.
With over 25 years of experience in software development and as the creator of CoreUI, I’ve accessed first elements countless times in components like breadcrumb navigation, carousel displays, and data lists where the initial item often has special significance or styling.
From my extensive expertise, the most straightforward and universally supported approach is using array index notation with [0]
to access the first position.
This method is direct, readable, and works consistently across all JavaScript environments without any dependencies.
Use array index notation [0]
to access the first element of an array.
const fruits = ['apple', 'banana', 'orange']
const firstFruit = fruits[0]
// Result: 'apple'
Array index notation uses square brackets with the position number to access specific elements, with arrays being zero-indexed meaning the first element is at position 0. In this example, fruits[0]
returns 'apple'
as it’s the first element in the array. This method returns undefined
if the array is empty or if you try to access an index that doesn’t exist. The approach is consistent whether you’re working with strings, numbers, objects, or any other data type stored in the array.
Best Practice Note:
This is the same approach we use in CoreUI components for accessing primary navigation items and displaying featured content throughout our component ecosystem.
Always check if the array has elements before accessing: array.length > 0 ? array[0] : null
. For a more functional approach with safety, consider array.at(0)
in modern environments, though [0]
remains the most widely supported and readable method.