How Lodash _.join Handles Null Values
When manipulating arrays in JavaScript, Lodash's _.join
method is a common utility used to concatenate elements into a single
string using a specified delimiter. If an array contains
null values, the behavior is often questioned by developers
expecting either literal string representations or completely stripped
delimiters. This article explains how _.join treats
null elements during execution, why this behavior occurs,
and how to adapt your code if you require a different output.
The Short Answer
When _.join encounters a null value in an
array, it converts the null to an empty string
("").
The element is not omitted from the final structure, meaning the delimiters surrounding that element remain intact. As a result, consecutive delimiters will appear side by side (or with surrounding whitespace depending on your separator).
const _ = require('lodash');
const array = ['alpha', null, 'beta'];
const result = _.join(array, '-');
console.log(result);
// Output: "alpha--beta"Why This Happens
Lodash implements _.join as a wrapper around the native
JavaScript Array.prototype.join() method. According to the
ECMAScript language specification, if any element of an array is
undefined or null, it is converted to an empty
string during the join operation rather than the string literal
"null" or "undefined".
How to Alter the Default Behavior
Depending on your use case, converting null to an empty
string may not be the desired outcome. Here are the two most common
alternatives:
1. Removing Null Values Completely
If you want to remove null values so that extra
separators do not appear, filter the array using _.compact
before joining:
const array = ['apple', null, 'banana', null, 'orange'];
const cleanString = _.join(_.compact(array), ', ');
console.log(cleanString);
// Output: "apple, banana, orange"2. Preserving the Literal Word "null"
If you need the output string to explicitly display the text
"null", map the values to strings prior to joining:
const array = ['user', null, 'admin'];
const literalString = _.join(array.map(String), ' | ');
console.log(literalString);
// Output: "user | null | admin"