Lodash _.head: Get the First Element of an Array

This article provides an overview of the _.head method in the Lodash JavaScript library, explaining how it simplifies retrieving the first element of an array. You will learn the mechanics behind the function, see how it compares to native JavaScript approaches, and discover how it prevents common runtime errors when working with empty, null, or undefined collections.

Understanding _.head in Lodash

The _.head function (also aliased as _.first) is a utility method that extracts the very first element of an array. Its syntax is straightforward:

_.head(array)

If the provided array contains elements, _.head returns the item at index 0. If the array is empty, or if the argument passed is null or undefined, the function safely returns undefined rather than throwing a runtime error.

How It Compares to Native JavaScript

In modern JavaScript, accessing the first element is commonly done via index notation or array destructuring:

const items = ['apple', 'banana', 'orange'];

// Index notation
const firstItem = items[0]; // 'apple'

// Destructuring
const [firstDestructured] = items; // 'apple'

While native approaches work well for guaranteed array instances, they introduce fragility when dealing with unpredictable data types. Attempting to access an index on null or undefined causes a fatal exception:

let data = null;

// Throws TypeError: Cannot read properties of null (reading '0')
const firstItem = data[0]; 

// Throws TypeError: data is not iterable
const [firstDestructured] = data; 

To guard against this natively, developers must include optional chaining or defensive type checks:

const safeFirst = data?.[0];

Lodash’s _.head abstracts these safety checks internally. It guarantees that any non-array input is handled gracefully without terminating execution:

const _ = require('lodash');

_.head(['apple', 'banana', 'orange']); // Returns 'apple'
_.head([]);                            // Returns undefined
_.head(null);                          // Returns undefined
_.head(undefined);                     // Returns undefined

Advantages in Functional Pipelines and Chaining

Beyond safe property access, _.head integrates cleanly into functional programming paradigms and Lodash method chains. When transforming data pipelines, using a named function is often cleaner than breaking out of the chain to use bracket notation:

const users = [
  { name: 'Alice', score: 85 },
  { name: 'Bob', score: 92 },
  { name: 'Charlie', score: 78 }
];

const topScorer = _(users)
  .orderBy(['score'], ['desc'])
  .head();

console.log(topScorer); // { name: 'Bob', score: 92 }

By providing defensive checks out of the box and fitting cleanly into point-free and chained workflows, _.head eliminates boilerplate validation code and makes array operations more predictable.