has()
has<
T>(object,key):boolean
Checks if an object has a property as its own (not inherited).
Works with objects created via Object.create(null).
Undefined/null values still return true if the property exists.
Type Parametersโ
T: T extends objectโ
The type of the object.
Parametersโ
object: Tโ
The object to check.
key: PropertyKeyโ
The property key to check for.
Returns: booleanโ
true if the object has the own property, false otherwise.
See Alsoโ
Object.hasOwn (ES2022 native alternative)
Sinceโ
2.0.0
Performanceโ
O(1) - Direct property lookup via Object.prototype.hasOwnProperty.
Also known asโ
has (Lodash, es-toolkit, Ramda, Effect) ยท โ (Remeda, Radashi, Modern Dash, Antfu)
Exampleโ
const obj = { a: 1, b: undefined };
has(obj, 'a'); // => true
has(obj, 'b'); // => true (property exists)
has(obj, 'c'); // => false
const bare = Object.create(null);
bare.x = 42;
has(bare, 'x'); // => true
How it works?โ
Checks if an object has a property as its own (not inherited).
Own vs Inheritedโ
Works with Object.create(null)โ
Unlike obj.hasOwnProperty(), has() works even when the prototype chain is broken.
Use Casesโ
Check property existence ๐โ
Safely check if an object has a property as its own key (not inherited). Essential for robust validation against prototypes.
if (has(data, 'result')) {
process(data.result);
}
Detect explicit undefinedโ
Distinguish between a property that exists but is undefined vs a missing property.
get() returns undefined in both cases, has() differentiates.
const obj = { start: undefined };
has(obj, 'start'); // true
has(obj, 'end'); // false
Validate dynamic keysโ
Check for the presence of a key when the key name is variable. Useful in loops or dynamic logic.
const key = getCurrentKey();
if (!has(cache, key)) {
loadData(key);
}