Lodash toString: Handling Null and Undefined Safely

In JavaScript development, converting data types to strings is a routine task that often introduces runtime exceptions when encountering missing values. This article explores how Lodash's _.toString utility safely handles null and undefined inputs, contrasting its behavior with native JavaScript alternatives and detailing how it prevents application crashes while maintaining predictable string outputs.

The Problem with Native JavaScript Type Conversion

Native JavaScript offers two primary mechanisms for converting values to strings, both of which introduce drawbacks when dealing with null and undefined:

  1. Object.prototype.toString(): Calling .toString() directly on a variable containing null or undefined throws an uncaught TypeError (e.g., Cannot read properties of null (reading 'toString')). This commonly breaks applications at runtime if API responses or inputs lack proper sanitization.
  2. String() constructor: While calling String(null) or String(undefined) avoids throwing an error, it coerces these values into literal strings: "null" and "undefined". In practical scenarios, such as rendering text in a user interface or writing to a database, displaying the word "null" is almost always undesired behavior.

How _.toString Resolves the Issue

Lodash’s _.toString function is designed as a defensive, safe conversion tool. It normalizes string conversion by treating both null and undefined as empty values rather than missing objects or literal text.

1. Returning Empty Strings for Nil Values

When provided with null or undefined, _.toString safely intercepts the value and returns an empty string (""):

const _ = require('lodash');

_.toString(null);
// => ''

_.toString(undefined);
// => ''

This behavior eliminates the risk of fatal TypeError exceptions and avoids the accidental propagation of literal "null" or "undefined" strings into UI components or external systems.

2. Implementation Under the Hood

Lodash achieves this through internal checks that identify null and undefined before attempting any standard operations. In Lodash’s source implementation, the logic operates conceptually as follows:

function baseToString(value) {
  if (typeof value === 'string') {
    return value;
  }
  if (value == null) {
    return '';
  }
  if (Array.isArray(value)) {
    return value.map(baseToString) + '';
  }
  // Handles symbols, -0, and standard objects
  return `${value}`;
}

Because value == null uses loose equality, it simultaneously matches both null and undefined, immediately routing them to return ''.

3. Safe Handling Inside Arrays

The safe conversion also applies recursively to arrays containing null or undefined elements:

_.toString([1, null, 2, undefined, 3]);
// => '1,,2,,3'

Instead of crashing or embedding "null", Lodash respects the empty state of those specific positions, matching the format native array joins typically produce without the associated risk.

4. Edge Cases: -0 and Symbols

Beyond null and undefined, _.toString also safely manages other JavaScript edge cases that break standard conversion:

Comparison Summary

Method null undefined Risk
val.toString() Throws TypeError Throws TypeError High (Crashes runtime)
String(val) "null" "undefined" Medium (Data pollution)
_.toString(val) "" "" None (Safe fallback)

Conclusion

Lodash's _.toString provides a fail-safe abstraction over standard JavaScript string coercion. By returning an empty string for null and undefined, it protects applications from runtime crashes and prevents unwanted literal string conversions, making it an ideal utility for processing untrusted or dynamic data.