How Lodash _.isSet Identifies ES6 Set Instances
This article explains how the Lodash utility library determines
whether a given value is an ES6 Set instance using the
_.isSet method. It details the internal checks Lodash
applies, including environment detection, Node.js native helpers, the
internal object tag resolution via getTag, and why standard
operators like instanceof are insufficient for robust
cross-environment type checking.
The Dual-Path Strategy
Under the hood, Lodash uses a dual-path implementation for
_.isSet. When executing in a Node.js environment, Lodash
attempts to leverage Node’s native type-checking utilities. In standard
browser environments or runtimes without native helpers, it falls back
to an internal helper function, typically named
baseIsSet.
var nodeIsSet = nodeUtil && nodeUtil.isSet;
var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;Native Node.js Checking
In environments where Node.js's built-in util.types
module is exposed, Lodash delegates the check to
util.types.isSet(). Because Node's internal binding checks
the underlying C++ wrapper directly, this approach offers high
performance and cannot be spoofed by modifying userland prototypes or
string tags.
The baseIsSet Fallback
In browser environments, Lodash relies on baseIsSet.
This function operates in two phases:
- Object-like check: It calls
isObjectLike(value), verifying that the value is non-null and that itstypeofreturns"object". - Tag verification: It calls
getTag(value)to verify if the internal type matches'[object Set]'.
function baseIsSet(value) {
return isObjectLike(value) && getTag(value) == '[object Set]';
}Resolving Object Tags with
getTag
The getTag helper wraps
Object.prototype.toString.call(value). In ECMAScript 2015
(ES6) and later, instances of Set have a built-in
Symbol.toStringTag property that evaluates to
'Set'. When passed to
Object.prototype.toString, the engine formats the output as
'[object Set]'.
Lodash accounts for edge cases where Symbol.toStringTag
might be altered or missing in older polyfilled environments. If symbols
are supported, Lodash temporarily masks or reads inherited symbol tags
to verify that the tag represents an authentic built-in object rather
than a standard object masquerading as a Set.
Why Lodash Avoids
instanceof Set
Lodash avoids using value instanceof Set because
instanceof fails across different execution contexts
(realms). For example, a Set created inside an
<iframe> or a Web Worker has a different prototype
chain than the Set constructor in the parent frame. By
inspecting the internal [[Class]] tag via
Object.prototype.toString (or native runtime bindings),
_.isSet guarantees accurate identification regardless of
context boundaries.