Example 1 — Own only
Object.hasOwn ignores the prototype.
JavaScript
console.log(Object.hasOwn({ a: 1 }, "a"));
console.log(Object.hasOwn({ a: 1 }, "toString")); How It Works
- hasOwn skips inherited keys.
The in operator returns true if a property name exists in an object or its prototype chain. For own properties only, prefer Object.hasOwn or hasOwnProperty.
const user = { name: "Ada" };
console.log("name" in user);
console.log("age" in user);
console.log("toString" in user); Object.hasOwn ignores the prototype.
console.log(Object.hasOwn({ a: 1 }, "a"));
console.log(Object.hasOwn({ a: 1 }, "toString")); Checks index existence.
console.log(0 in ["x"]);
console.log(1 in ["x"]); Key is gone.
const o = { a: 1 }; delete o.a; console.log("a" in o); CODETOFUN NEWS
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
6 people found this page helpful