How Lodash isEmpty Evaluates JavaScript Map Objects
This article explains the internal mechanism used by the Lodash
library when _.isEmpty evaluates ECMAScript 2015 (ES6)
Map instances. It details the exact property checks and
type-tag assertions Lodash executes to determine whether a
Map contains no entries and should return
true.
The Core Property:
size
When evaluating a Map object, Lodash's
_.isEmpty relies directly on the standard size
property. Specifically, after verifying the object's type, Lodash
returns the result of:
!value.sizeIf a Map lacks entries, its size property
returns 0. In JavaScript, 0 is a falsy value,
so !0 evaluates strictly to true. Conversely,
if the Map contains one or more key-value pairs,
size returns an integer greater than 0,
causing !value.size to return false.
The Step-by-Step Evaluation Pipeline
Lodash does not inspect standard enumerable object keys for a
Map as it would for a plain object. The internal execution
path in lodash.isEmpty proceeds through three distinct
phases:
1. Null and Undefined Guard
Lodash first ensures that the supplied value is not null
or undefined:
if (value == null) {
return true;
}2. Type Identification via Internal Tags
Because an ES6 Map does not have a numeric
.length property, it bypasses array-like checks
(isArrayLike). Lodash then identifies the internal
classification tag of the object using an internal helper
(getTag or baseGetTag), which resolves the
object's Symbol.toStringTag or uses
Object.prototype.toString.call(value).
Lodash checks if this resolved tag matches the internal constant for maps:
var mapTag = '[object Map]';
var tag = getTag(value);3. Size Evaluation
Once the tag matches [object Map] (or
[object Set]), Lodash bypasses standard
for...in key iterations and property descriptor checks,
evaluating the collection solely by reading .size:
if (tag == mapTag || tag == setTag) {
return !value.size;
}Why Plain Key Checks Are Bypassed
Traditional JavaScript objects store data as string- or symbol-keyed
properties, which Lodash evaluates using hasOwnProperty
iterations or Object.keys(). However, ECMAScript
Map objects store entries in an internal slot
([[MapData]]), meaning entries are not registered as
enumerable properties on the instance itself.
Lodash bypasses its standard key-enumeration fallback
(for (var key in value)) for Map objects
because Object.keys(new Map([['a', 1]])) returns an empty
array []. Checking the explicit size property
is the only standard-compliant way to determine entry presence without
iterating over the map’s entries using
Map.prototype.entries().