What Defines a WeakMap in Lodash _.isWeakMap

The _.isWeakMap method in the Lodash JavaScript library determines whether a given value is classified as a native WeakMap object. This article examines the specific internal checks Lodash uses to validate a WeakMap, the difference between actual WeakMap instances and lookalike objects, and how the underlying mechanism ensures accurate type detection across different JavaScript runtime environments.

In JavaScript, a WeakMap is a collection of key/value pairs where keys must be objects (or non-registered symbols in modern ECMAScript) and are held weakly, meaning they do not prevent garbage collection if there are no other references to the key. Because of these distinct runtime characteristics, standard type checking like typeof simply yields "object", which is insufficient for distinguishing a WeakMap from regular objects, standard Map instances, or arrays.

To determine if an entity is a WeakMap, Lodash's _.isWeakMap performs two primary checks:

  1. Object-Like Validation: It verifies that the passed value is "object-like" using Lodash's internal isObjectLike function. The value must not be null and its typeof result must be "object".
  2. Internal Tag Resolution: It inspects the internal [[Class]] tag of the object using an internal getTag function (an abstraction over Object.prototype.toString.call(value) and Symbol.toStringTag).

For _.isWeakMap(value) to return true, the resolved tag must strictly match '[object WeakMap]'.

const _ = require('lodash');

const weakMap = new WeakMap();
const standardMap = new Map();

_.isWeakMap(weakMap);       // => true
_.isWeakMap(standardMap);   // => false
_.isWeakMap({});            // => false
_.isWeakMap(null);          // => false

Custom objects or polyfills that mimic the WeakMap API (such as having .get(), .set(), .has(), and .delete() methods) will still return false unless they accurately yield '[object WeakMap]' through their Symbol.toStringTag property. Standard Map, Set, WeakSet, and plain objects fail this check because their internal tag representations resolve differently (e.g., '[object Map]' or '[object Object]'). Consequently, _.isWeakMap guarantees that the target value natively adheres to the memory-management and key-constraint behaviors defined by the ECMAScript WeakMap specification.