Technical skill practice

JavaScript Has Own Property: Keep Inheritance and Falsy Values Separate

Object.hasOwn checks whether a property belongs directly to an object. It does not require the property value to be truthy, and it does not treat an inherited property as an own one.

The task

Inspect local preferences inheriting a theme default. Include an owned false flag and a field named hasOwnProperty to demonstrate why directly calling that name is fragile.

Runnable Node 22 example

const assert = require('node:assert/strict');

const preferences = Object.create({theme: 'light'});
preferences.enabled = false;
preferences.hasOwnProperty = 'user data';
assert.equal(Object.hasOwn(preferences, 'enabled'), true);
assert.equal(Boolean(preferences.enabled), false);
assert.equal(Object.hasOwn(preferences, 'theme'), false);
assert.equal('theme' in preferences, true);
assert.equal(preferences.theme, 'light');
assert.throws(() => preferences.hasOwnProperty('enabled'), TypeError);
console.log(`enabledOwn=${Object.hasOwn(preferences, 'enabled')}; themeOwn=${Object.hasOwn(preferences, 'theme')}`);

Expected output and explanation

The false enabled value is still an owned setting. Theme can be found by lookup and the in operator, yet is inherited rather than owned. Those are compatible results because the operations ask different questions.

The data field shadows the usual method name, so attempting to call it throws. The static Object.hasOwn operation does not depend on that field being a callable method. It is also suitable for a null-prototype dictionary when used with the intended object input.

Output from the example

enabledOwn=true; themeOwn=false

Pitfall to check

An own property does not guarantee a valid value or permission to apply it. Validate allowed keys and value types separately. Counting all keys to define an empty object is a different task from checking one named setting.

Questions, answered

Does the in operator only check own properties?

No. The example finds the inherited theme with in. Use an own-property test when inherited defaults must remain distinguishable.

Sources and examples

ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.

Your experience. A complete resume.

Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.

Free account required. Free-plan PDF exports include a watermark.