@rbxts/jsnatives
Object.hasOwn
Determines whether an object has a property with the specified name.
Signature
function hasOwn<T>(obj: ReadonlyArray<T>, key: number): booleanfunction hasOwn<T>(obj: ReadonlySet<T>, key: T): booleanfunction hasOwn<K, T>(obj: ReadonlyMap<K, T>, key: K): booleanfunction hasOwn<T extends object>(obj: T, key: keyof T): obj is T & Record<keyof T, NonNullable<T[keyof T]>>
Description
The Object.hasOwn()
method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it). The method is type-aware and works differently based on the object type:
- For arrays: checks if the specified index exists
- For sets: checks if the specified value exists
- For maps: checks if the specified key exists
- For objects: checks if the specified property exists
Examples
Object property check
const obj = {a: 1, b: 2, c: 3};
print(Object.hasOwn(obj, "a")); // trueprint(Object.hasOwn(obj, "b")); // trueprint(Object.hasOwn(obj, "c")); // trueprint(Object.hasOwn(obj, "d")); // false
Proxy property check
const proxiedObj = new Proxy({}, { ownKeys: () => ["a", "b", "c"]});
print(Object.hasOwn(proxiedObj, "a")); // trueprint(Object.hasOwn(proxiedObj, "b")); // trueprint(Object.hasOwn(proxiedObj, "c")); // trueprint(Object.hasOwn(proxiedObj, "d")); // false
Set value check
const set = new Set([1, 2, 3]);
print(Object.hasOwn(set, 1)); // trueprint(Object.hasOwn(set, 2)); // trueprint(Object.hasOwn(set, 3)); // trueprint(Object.hasOwn(set, 4)); // false
Map key check
const map = new Map([["a", 1], ["b", 2], ["c", 3]]);
print(Object.hasOwn(map, "a")); // trueprint(Object.hasOwn(map, "b")); // trueprint(Object.hasOwn(map, "c")); // trueprint(Object.hasOwn(map, "d")); // false
Array index check
const array = [1, 2, 3];
print(Object.hasOwn(array, 0)); // trueprint(Object.hasOwn(array, 1)); // trueprint(Object.hasOwn(array, 2)); // trueprint(Object.hasOwn(array, 3)); // false