How do you check whether a specific key exists in a JavaScript object?
Use **Object.hasOwn(obj, “key”)** (ES2022) to check for own properties safely without matching inherited prototype keys like toString, or use the **“key” in obj`** operator if inherited properties should also count.
Object.hasOwn() vs. in Operator
const post = { id: 1, title: "What is JavaScript?" };
// 1. Recommended: Checks ONLY own properties (ignores Object.prototype)
console.log(Object.hasOwn(post, "title")); // true
console.log(Object.hasOwn(post, "toString")); // false
// 2. 'in' operator: Checks own AND inherited prototype properties
console.log("title" in post); // true
console.log("toString" in post); // true'
You must log in or register to comment.
