Skip to content
jshacks.dev
Fundamentals

How to Check If a Key Exists in an Object in JavaScript

Use Object.hasOwn(obj, key) for own keys and the in operator to include inherited ones. See why comparing to undefined fails, and Map lookups for user keys.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Node.js, Vite, npm and TypeScript logos.

Reading a property that is not there does not fail in JavaScript, it returns undefined, and that quiet answer is the source of every bug in key-existence code. A value of undefined could mean the key is missing or that the key is present and holds undefined, and the two are different facts. The language has several ways to ask the real question, each with its own idea of what "exists" means: the key is on the object itself, the key is on the object or anywhere up its prototype chain, or the key has a value other than undefined. This post shows the check for each meaning, the one to use by default, why hasOwnProperty is no longer the recommended spelling, what happens with keys such as constructor and __proto__, how arrays and Map fit in, and the mistakes that look right in review. The examples run on Node.js 24.

Use Object.hasOwn

JavaScript
const user = { name: "Ada", email: null, nickname: undefined };

console.log(Object.hasOwn(user, "name"));
console.log(Object.hasOwn(user, "email"));
console.log(Object.hasOwn(user, "nickname"));
console.log(Object.hasOwn(user, "age"));
console.log(Object.hasOwn(user, "toString"));
Text
true
true
true
false
false

Object.hasOwn(object, key) is true when the object has its own property with that name, whatever its value, so null and undefined values count, and false otherwise. The last line shows that inherited properties do not count: toString exists on every object, and it lives on Object.prototype, not on user. This is the answer to "does this record contain this field", and it is the check to use by default. It was added in ES2022 and works in Node.js 16.9 and later and in all current browsers.

The in operator includes inherited keys

JavaScript
const base = { inherited: 1 };
const child = Object.create(base);
child.own = 2;

console.log("own" in child, "inherited" in child, "toString" in child, "missing" in child);
console.log(Object.hasOwn(child, "own"), Object.hasOwn(child, "inherited"));
Text
true true true false
true false

The in operator searches the whole prototype chain, so it finds own on the object, inherited on its prototype, and toString on Object.prototype. Use it when you want the answer to "can I read this property and get a real value", including inherited methods, such as checking whether an object has a then method. Use Object.hasOwn() for data, where only the object's own fields matter. Mixing them up is how a user-supplied key of "constructor" appears to exist in an empty object.

Why comparing to undefined is wrong

JavaScript
const settings = { theme: undefined, volume: 0, label: "" };

const exists = (object, key) => object[key] !== undefined;

console.log(exists(settings, "theme"), Object.hasOwn(settings, "theme"));
console.log(exists(settings, "volume"), exists(settings, "label"));
console.log(exists(settings, "missing"));

console.log(settings.theme ? "truthy" : "falsy", settings.volume ? "truthy" : "falsy");
Text
false true
true true
false
falsy falsy

The comparison with undefined fails for a key that is present and holds undefined: theme exists and the helper says it does not. It also reports inherited keys as existing. A truthiness test is worse: volume is 0 and label is an empty string, both are falsy, and both exist. Use !== undefined only when you mean "this has a usable value", and not for existence. If a missing key and an undefined value should be treated the same, write that deliberately, with ?? for a default.

Optional chaining and nested keys

For a key that may be several levels deep, optional chaining avoids a TypeError at each missing level.

JavaScript
const config = { server: { port: 8080, tls: null } };

console.log(config.server?.port, config.database?.host, config.server?.tls?.cert);
console.log(config?.server?.port ?? 3000, config.cache?.ttl ?? 60);

function hasPath(object, ...keys) {
  let current = object;
  for (const key of keys) {
    if (current === null || typeof current !== "object" || !Object.hasOwn(current, key)) return false;
    current = current[key];
  }
  return true;
}

console.log(hasPath(config, "server", "port"), hasPath(config, "server", "tls"), hasPath(config, "server", "tls", "cert"));
Text
8080 undefined undefined
8080 60
true true false

?. stops at a missing link and returns undefined, and ?? supplies the default. They answer "what is the value or its default", and not "does the key exist": config.server?.tls?.cert is undefined whether tls is null or cert is missing. The hasPath helper walks a path and checks each step with Object.hasOwn(), which gives an exact answer. In the example, tls exists with the value null, so the path server.tls exists and server.tls.cert does not.

Why hasOwnProperty is no longer the best spelling

hasOwnProperty was the standard check for twenty years, called as a method on the object. Two problems made Object.hasOwn the better choice.

JavaScript
const dictionary = Object.create(null);
dictionary.apple = 1;

console.log(Object.hasOwn(dictionary, "apple"));
console.log(typeof dictionary.hasOwnProperty);

const sneaky = { hasOwnProperty: () => true, real: 1 };

console.log(sneaky.hasOwnProperty("anything"));
console.log(Object.hasOwn(sneaky, "anything"));
console.log(Object.prototype.hasOwnProperty.call(sneaky, "anything"));
Text
true
undefined
true
false
false

An object created with Object.create(null) has no prototype and so no hasOwnProperty method: calling it throws. An object with its own property called hasOwnProperty, which can happen when keys come from user data, replaces the method, and the answer is wrong. The older safe form, Object.prototype.hasOwnProperty.call(object, key), works for both and is long. Object.hasOwn(object, key) is the same thing in one call, and the one to write now.

Dangerous keys from user data

Keys that come from outside, a query string or a JSON body, can be anything, including names that exist on every object.

JavaScript
const counts = {};
const incoming = ["apple", "constructor", "apple", "toString"];

for (const word of incoming) {
  counts[word] = (counts[word] ?? 0) + 1;
}

console.log(counts);

const safeCounts = new Map();
for (const word of incoming) {
  safeCounts.set(word, (safeCounts.get(word) ?? 0) + 1);
}

console.log(safeCounts);
console.log(safeCounts.has("constructor"), safeCounts.has("missing"));
Text
{
  apple: 2,
  constructor: 'function Object() { [native code] }1',
  toString: 'function toString() { [native code] }1'
}
Map(3) { 'apple' => 2, 'constructor' => 1, 'toString' => 1 }
true false

On a plain object, reading counts["constructor"] finds the inherited Object function, which is not undefined, so ?? keeps it and + 1 turns it into the string "function Object() { [native code] }1". The counts for those two words are garbage. A Map has no inherited keys to confuse the lookup, and has() answers exactly. For dictionaries with arbitrary keys, use a Map, or an object with a null prototype and Object.hasOwn(), and never trust a plain object as a lookup table for data you do not control.

The __proto__ key

JavaScript
const parsed = JSON.parse('{"__proto__": {"admin": true}, "name": "x"}');

console.log(Object.hasOwn(parsed, "__proto__"), parsed.admin, Object.keys(parsed));

const assigned = {};
assigned["__proto__"] = { admin: true };

console.log(Object.hasOwn(assigned, "__proto__"), assigned.admin, Object.keys(assigned));
Text
true undefined [ '__proto__', 'name' ]
false true []

JSON.parse creates an own property called __proto__ as ordinary data, so parsed.admin is undefined. A plain assignment to __proto__ is different: it invokes a setter that changes the object's prototype, and assigned.admin becomes true by inheritance. Code that copies keys from untrusted input into an object with assignment can be attacked this way, which is called prototype pollution when the target is a shared prototype. Use Object.hasOwn() to test keys, a Map or a null-prototype object for storage, and reject or skip the key __proto__ when merging.

Arrays and Map

JavaScript
const list = ["a", undefined, "c"];
list[5] = "f";

console.log(1 in list, 3 in list, 5 in list, list.length);
console.log(Object.hasOwn(list, 1), Object.hasOwn(list, 3));
console.log(list.includes(undefined), list.indexOf("c"));

const map = new Map([["key", undefined]]);

console.log(map.has("key"), map.get("key"), map.has("other"));
Text
true false true 6
true false
true 2
true undefined false

For arrays, the in operator and Object.hasOwn() test for an index. Index 1 holds undefined and exists, and index 3 is a hole, an index that was never assigned, which does not. To ask whether a value is in the array, use includes(), which treats holes as undefined, so it finds undefined, and indexOf("c") is 2.

Map.has(key) is the existence check for maps, and it is exact: the key "key" exists with the value undefined, and "other" does not, so get() alone could not tell them apart.

A mistake we hit: the truthiness check on a flag

JavaScript
function applyOptions(options) {
  const verbose = options.verbose ? true : false;
  const retries = options.retries || 3;
  const timeout = options.timeout ?? 1000;
  const label = Object.hasOwn(options, "label") ? options.label : "default";
  return { verbose, retries, timeout, label };
}

console.log(applyOptions({ verbose: false, retries: 0, timeout: 0, label: "" }));
console.log(applyOptions({}));
Text
{ verbose: false, retries: 3, timeout: 0, label: '' }
{ verbose: false, retries: 3, timeout: 1000, label: 'default' }

The caller passed retries: 0 to turn retries off, and the || operator treated the zero as missing and replaced it with 3. The ?? operator kept timeout: 0, which is a valid value, and the Object.hasOwn() check kept the empty label. We had an incident where "disable retries" did not disable them. Pick the operator that matches the question: || for "falsy means missing", ?? for "null and undefined mean missing", and Object.hasOwn() for "the key was provided at all".

Choosing between the checks

You want to knowUse
The object itself has the keyObject.hasOwn(object, key)
The key exists on the object or its prototype chainkey in object
The value is not undefinedobject[key] !== undefined
A value or a defaultobject[key] ?? fallback
A key at the end of a pathobject.a?.b?.c, or a hasPath helper
A key in a mapmap.has(key)
An index in an arrayObject.hasOwn(array, index) or index in array

Practical rules we follow

Use Object.hasOwn() for data. Use in only when inherited properties should count. Never use truthiness or !== undefined to test existence. Use ?? for defaults and || only for falsy checks. Store untrusted keys in a Map or a null-prototype object. Skip __proto__ when merging. And write the check that matches the question in words before choosing the operator.

Where these checks stop

They test existence at the moment of the call, and say nothing about the type of the value. A getter on an object can throw when read, and in does not call it, while a read does. A Proxy can answer each check differently, through its has and getOwnPropertyDescriptor traps, as covered in [the has trap](/library/javascript-proxy-has-trap). The reference is in the MDN Object.hasOwn page and the [MDN in operator page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in).

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.