Lodash _.first: Convenient Array Access in JavaScript
The _.first method in the Lodash JavaScript library
provides a clean, expressive way to retrieve the initial element of an
array without relying on traditional bracket notation. This article
explores how _.first functions as an intuitive alias for
Lodash's _.head, how it improves code readability and
safety when handling null or undefined values, and why it remains a
valuable utility for developers seeking cleaner functional programming
patterns.
An Alias for _.head
In Lodash, _.first is an alias for _.head.
Both methods perform the exact same operation: returning the first
element of a given collection or array. Lodash maintains this alias
primarily for semantic flexibility and backwards compatibility with
libraries like Underscore.js. Developers who prefer descriptive naming
conventions often choose _.first because it immediately
conveys intent to anyone reading the codebase.
const _ = require('lodash');
const numbers = [10, 20, 30, 40];
console.log(_.first(numbers)); // 10
console.log(_.head(numbers)); // 10Safe Array Handling
One major advantage of using _.first over standard
JavaScript bracket notation (array[0]) is built-in null
safety. When working with dynamic data, attempting to read the index of
an undefined or null variable directly causes a runtime
TypeError.
// Native JavaScript approach
let items = null;
// items[0]; // Throws TypeError: Cannot read properties of null
// Lodash approach
console.log(_.first(items)); // Returns undefined safelyIf the input is empty, null, or undefined,
_.first gracefully returns undefined rather
than halting program execution. This reduces the need for defensive
checks such as items && items[0].
Readability and Functional Pipelines
Using numerical index access like array[0] can obscure
developer intent, especially in complex operations. The identifier
[0] signifies a data structure's offset, whereas
_.first() signifies an explicit goal: obtaining the leading
value.
This semantic clarity becomes particularly useful in method chains and functional pipelines:
const users = [
{ name: 'Alice', active: true },
{ name: 'Bob', active: false },
{ name: 'Charlie', active: true }
];
const firstActiveUser = _.chain(users)
.filter('active')
.first()
.value();
console.log(firstActiveUser); // { name: 'Alice', active: true }By presenting a descriptive method name, _.first ensures
that data transformations remain readable, predictable, and resilient
against unexpected inputs.