---
title: "How do you check if a key exists in a JavaScript object?"
description: "Use Object.hasOwn(), the in operator or hasOwnProperty to test for a key, and learn when each one gives a different result."
url: "https://bugsee.com/answers/javascript/check-if-a-key-exists-in-an-object/"
---

# How do you check if a key exists in a JavaScript object?

Use `Object.hasOwn(obj, key)` to test for the object's own keys, or the `in` operator if inherited keys should count too.

There are three common checks, and they differ in how they treat inherited properties and keys whose value is `undefined`.

```js
const user = { name: "Ada", email: undefined };

Object.hasOwn(user, "name");      // true  (own key)
Object.hasOwn(user, "email");     // true  (key exists, value is undefined)
Object.hasOwn(user, "toString");  // false (inherited, not own)

"toString" in user;               // true  (in also walks the prototype chain)
user.email !== undefined;         // false (cannot tell "missing" from "undefined")
```

Avoid comparing the value to `undefined` when you really want to know whether the key is there. A key can exist with an `undefined` value, and the comparison will report it as missing.

- `Object.hasOwn(obj, key)`: own keys only, and safe for objects created with `Object.create(null)`.
- `key in obj`: own and inherited keys.
- `obj.hasOwnProperty(key)`: the older form, which fails on objects without a prototype.

## Related questions

- [How do you remove duplicates from an array in JavaScript?](https://bugsee.com/answers/javascript/remove-duplicates-from-an-array/)
- [How do you check if a variable is undefined in JavaScript?](https://bugsee.com/answers/javascript/check-if-a-variable-is-undefined/)
