Lodash isEmpty Behavior on Maps with Undefined Values

In Lodash, the _.isEmpty utility determines whether a collection, object, map, or set has no elements. When evaluating a JavaScript Map where keys exist but their associated values are strictly undefined, _.isEmpty evaluates the data structure solely on its entry count, returning false. This article details how the method handles this condition under the hood, provides code examples demonstrating this behavior, and shows alternative ways to detect maps with only undefined values.

How _.isEmpty Evaluates a Map

Lodash’s _.isEmpty does not inspect the underlying values assigned to the entries within a Map. Instead, it checks the internal size of the collection. For built-in collection types such as Map and Set, Lodash accesses the native size property.

If map.size is greater than 0, _.isEmpty considers the structure populated and returns false. Because inserting a key with an undefined value still registers as a valid entry in a JavaScript Map, the size property increments accordingly.

Code Demonstration

The following example illustrates how _.isEmpty processes a Map holding strictly undefined values:

const _ = require('lodash');

// Create a map and insert keys with strictly undefined values
const map = new Map();
map.set('firstKey', undefined);
map.set('secondKey', undefined);

console.log(map.size); // Output: 2
console.log(_.isEmpty(map)); // Output: false

Even though the values associated with 'firstKey' and 'secondKey' are undefined, the map contains two entries. Consequently, Lodash treats the Map as non-empty.

Why JavaScript Maps Retain undefined Values

In native JavaScript, a Map holds key-value pairs where keys and values can be any type. Setting a key to undefined is fundamentally distinct from deleting the key.

Because _.isEmpty is designed to detect the absence of data entries rather than the semantic quality of those entries, it adheres strictly to the existence of entries.

Checking for Maps with Only Undefined Values

If an application requires checking whether a Map is either empty or exclusively populated by undefined values, _.isEmpty alone is insufficient. Native array methods or custom checks should be used instead:

function isMapEffectivelyEmpty(map) {
  if (!(map instanceof Map) || map.size === 0) {
    return true;
  }
  
  for (const value of map.values()) {
    if (value !== undefined) {
      return false;
    }
  }
  
  return true;
}

const emptyValuesMap = new Map([
  ['a', undefined],
  ['b', undefined]
]);

console.log(isMapEffectivelyEmpty(emptyValuesMap)); // Output: true

This approach manually inspects map.values() to ensure that keys mapped strictly to undefined can be treated as empty when your specific domain logic requires it.