How Lodash _.forOwn Iterates Over Direct Properties

Lodash's _.forOwn method provides a reliable way to iterate exclusively over an object's own enumerable properties while strictly ignoring inherited properties from its prototype chain. Unlike JavaScript's traditional for...in loop or Lodash's _.forIn, which both traverse the entire prototype hierarchy, _.forOwn confines execution solely to keys assigned directly to the object instance. This article explains how _.forOwn enforces this boundary under the hood using native property extraction and prototype-safe property verification.

The Prototype Traversal Problem

In standard JavaScript, using a for...in loop iterates over all enumerable properties of an object, including properties inherited through its prototype chain. For example, if a custom property or utility function is added to Object.prototype, a standard for...in or _.forIn loop will execute for that property. This often results in unintended side effects, requiring developers to manually filter properties.

Underlying Mechanism: Own Keys Retrieval

_.forOwn limits its iteration by leveraging property enumeration routines that capture only own properties. Internally, Lodash delegates the key extraction to internal utility functions (such as baseForOwn and keys).

Instead of walking the prototype chain, Lodash utilizes native methods equivalent to Object.keys(). Native Object.keys() is defined by the ECMAScript specification to return an array of a given object's own enumerable string-keyed property names. Because this array is generated before iteration begins, inherited properties are completely excluded from the list of keys to be processed.

Prototype-Safe Key Filtering

To ensure compatibility across different JavaScript environments and edge cases—such as objects with no prototype created via Object.create(null) or objects where the hasOwnProperty property has been overwritten—Lodash employs a safe check equivalent to:

Object.prototype.hasOwnProperty.call(object, key);

By borrowing hasOwnProperty directly from Object.prototype, Lodash safely verifies whether a key belongs directly to the instance, independent of any shadowing on the target object itself.

Comparison: _.forIn vs _.forOwn

The distinction between Lodash's iteration methods highlights this constraint:

By extracting only direct keys via Object.keys() and guarding iteration against prototype inheritance, _.forOwn ensures predictable data handling, making it the safer alternative for dictionary and plain-object traversal in JavaScript applications.