How do you check whether a specific key exists in a JavaScript object? | A1Lab@FahadM to JavaScriptEnglish •
edit-2
12 days ago

How do you check whether a specific key exists in a JavaScript object?

message-square
0

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'