Emmanuel Akinfulubi

JavaScriptObject

Four ways to check if a property exists in JavaScript

Intermediate · 3 min read

"Does this object have a driver property?" sounds like a yes-or-no question. In JavaScript there are four common ways to ask it, and they don't always agree. Picking the wrong one leads to bugs like a form that thinks a field is missing when it is there but empty.

In this tutorial you will write all four checks side by side, then try them on the cases that tell them apart: a property set to undefined, an inherited property, and an object with no prototype at all. By the end you will know which one to reach for. You need to know objects and functions.

Own and inherited properties

An object's own properties are the ones it holds itself. It can also inherit properties from its prototype, another object it borrows from. Object.create(proto) makes a new object that inherits from proto:

JavaScript

const inheriting = Object.create({ fare: 4500 });
inheriting.plate = 'ABJ-772-KM';
console.log(inheriting.fare); // 4500

fare is readable, but it belongs to the prototype, not to inheriting.

The four checks

JavaScript

const byUndefined = (obj, key) => obj[key] !== undefined;      // careless
const byIn = (obj, key) => key in obj;                          // own + inherited
const byHasOwn = (obj, key) => Object.hasOwn(obj, key);         // own only
const byKeys = (obj, key) => Object.keys(obj).includes(key);    // own + enumerable

Each comment says what the check really asks. Keep them in mind as we test.

Here is the exercise. Try it yourself first if you like, or follow along below.

17 Does the object have this property?

fair

Check whether an object contains a given property. There are four ways, and they answer four slightly different questions.

Stuck? Three hints, smallest first
  1. 1. obj.key !== undefined is the tempting one, and it is wrong when the value is undefined.
  2. 2. in includes inherited properties; Object.hasOwn does not.
  3. 3. Object.hasOwn is the modern replacement for obj.hasOwnProperty(key), and it works on prototype-less objects.

Step 1: a property that is plainly there

Step 1

const bus = { plate: 'LAG-441-XA', driver: undefined };
console.log(byIn(bus, 'plate'), byHasOwn(bus, 'plate'), byKeys(bus, 'plate')); // true true true
console.log(byIn(bus, 'conductor')); // false

For an ordinary property they all agree, and a missing one is missing. The differences only show up in the odd cases.

Step 2: a property that holds undefined

bus.driver exists, but its value is undefined. Maybe no driver has been assigned yet.

Step 2

console.log(byUndefined(bus, 'driver')); // false
console.log(byIn(bus, 'driver'));        // true

The careless check says "no", because reading a missing property also gives undefined, so it can't tell "missing" from "present but empty". in asks whether the key exists, and it does. This is the case where the difference really matters, so don't use the !== undefined check to test for a key.

Step 3: an inherited property

Step 3

console.log(byIn(inheriting, 'fare'));     // true
console.log(byHasOwn(inheriting, 'fare')); // false
console.log(byIn({}, 'toString'));         // true
console.log(byHasOwn({}, 'toString'));     // false

in follows the prototype chain, so it finds fare, and even toString, which every plain object inherits. Object.hasOwn only looks at the object itself. Usually "does this object have it?" means own properties, so Object.hasOwn is the safer default.

Step 4: a hidden property

A property can be non-enumerable, which means lists like Object.keys skip it. Object.defineProperty makes one:

Step 4

const hidden = Object.defineProperty({}, 'x', { value: 1 });
console.log(byHasOwn(hidden, 'x')); // true
console.log(byKeys(hidden, 'x'));   // false

The Object.keys check misses it. It also does more work than needed: it builds an array of every key just to search it.

Step 5: an object with no prototype

Before Object.hasOwn existed, people wrote obj.hasOwnProperty(key). That method is inherited from Object.prototype. An object made with Object.create(null) has no prototype, so it doesn't have the method:

Step 5

const bare = Object.create(null);
bare.plate = 'ENU-318-PH';
console.log(typeof bare.hasOwnProperty); // undefined
console.log(byHasOwn(bare, 'plate'));     // true

Calling bare.hasOwnProperty('plate') would throw a TypeError, because there is no such function. Object.hasOwn is a function on Object itself, so it works on any object. It also can't be fooled by an object that has its own property called hasOwnProperty.

Which one to use

  • Object.hasOwn(obj, key): the default. Own properties only, works everywhere.
  • key in obj: when inherited properties should count too.
  • Object.keys(obj).includes(key): rarely; only if hidden properties must not count.
  • obj[key] !== undefined: not for checking keys.

The full solution

The panel defines the four checks and runs them on the bus, the inheriting object and the prototype-less object, printing where they disagree. Press Run to see the results.

The answer

const byUndefined = (obj, key) => obj[key] !== undefined;      // careless
const byIn = (obj, key) => key in obj;                          // own + inherited
const byHasOwn = (obj, key) => Object.hasOwn(obj, key);         // own only
const byKeys = (obj, key) => Object.keys(obj).includes(key);    // own + enumerable

const bus = { plate: 'LAG-441-XA', driver: undefined };
const inheriting = Object.create({ fare: 4500 });
inheriting.plate = 'ABJ-772-KM';

// hasOwnProperty is inherited, so an object without a prototype does not have it.
const bare = Object.create(null);
bare.plate = 'ENU-318-PH';
const bareHasOwnProperty = typeof bare.hasOwnProperty;

console.log('--- a property whose value IS undefined ---');
console.log('driver !== undefined:', byUndefined(bus, 'driver'), '<- says no, wrongly');
console.log("'driver' in bus     :", byIn(bus, 'driver'), '<- says yes, correctly');
console.log('--- an inherited property ---');
console.log("'fare' in inheriting     :", byIn(inheriting, 'fare'));
console.log('Object.hasOwn(.., fare)  :', byHasOwn(inheriting, 'fare'), '<- own only');
console.log('--- a prototype-less object ---');
console.log('bare.hasOwnProperty is', bareHasOwnProperty, '<- calling it would throw');
console.log('Object.hasOwn still works:', byHasOwn(bare, 'plate'));

Output


      
17 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 17 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

17 checks

test('a present property is found by all four', ['byIn', 'byHasOwn', 'byKeys'].length, 3);
test('in finds it', byIn(bus, 'plate'), true);
test('hasOwn finds it', byHasOwn(bus, 'plate'), true);
test('keys finds it', byKeys(bus, 'plate'), true);
test('an absent property is not found', byIn(bus, 'conductor'), false);
test('a property set to undefined IS present', byIn(bus, 'driver'), true);
test('but the careless check says it is not', byUndefined(bus, 'driver'), false);
test('which is the whole reason not to use it', byUndefined(bus, 'driver') !== byIn(bus, 'driver'), true);
test('in finds an inherited property', byIn(inheriting, 'fare'), true);
test('hasOwn does not', byHasOwn(inheriting, 'fare'), false);
test('both find the own one', byIn(inheriting, 'plate') && byHasOwn(inheriting, 'plate'), true);
test('in also finds inherited built-ins', byIn({}, 'toString'), true);
test('while hasOwn does not', byHasOwn({}, 'toString'), false);
test('a prototype-less object has no hasOwnProperty method', bareHasOwnProperty, 'undefined');
test('but Object.hasOwn works on it anyway', byHasOwn(bare, 'plate'), true);
test('a non-enumerable property is found by hasOwn', byHasOwn(Object.defineProperty({}, 'x', { value: 1 }), 'x'), true);
test('but not by Object.keys', byKeys(Object.defineProperty({}, 'x', { value: 1 }), 'x'), false);

Pick by the question you are asking. Object.hasOwn(obj, key) is the right default: own properties only, works on prototype-less objects, and unlike obj.hasOwnProperty(key) it cannot be broken by an object that happens to have its own property called hasOwnProperty. Use in when inherited properties should count.

Do not use obj[key] !== undefined. The assertions show it reporting false for a property that exists and holds undefined — the exact case where knowing whether the key is present actually matters.

Common mistakes

  • Testing obj[key] !== undefined. It says false for a key that exists and holds undefined.
  • Using in when you mean "own". It also finds inherited properties like toString.
  • Calling obj.hasOwnProperty(key). It fails on objects with no prototype. Use Object.hasOwn.

Try it yourself

  1. Run all four checks on { count: 0 } with the key 'count'. Do they agree?
  2. Make an object with its own property hasOwnProperty: () => true, then compare obj.hasOwnProperty('nope') with Object.hasOwn(obj, 'nope').
  3. Write missingFields(obj, fields) that returns the field names obj doesn't own.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.