Check Imported Object Fields with Object.hasOwn

A settings importer uses if (settings.sound) to decide whether the user supplied a sound preference. An explicit false disappears into the default, and an inherited value can accidentally count as imported data.

Use Object.hasOwn() to ask whether a field belongs to the object itself. Then validate its value separately. This recipe targets modern browsers or Node.js 20 or later and uses a single optional Boolean field to keep the input policy explicit.

Reproduce the Presence Mistake

Run this example:

1
2
3
4
5
6
const settings = Object.create({ sound: true });
console.log("sound" in settings);             // true
console.log(Object.hasOwn(settings, "sound")); // false
settings.sound = false;
console.log(Boolean(settings.sound));         // false
console.log(Object.hasOwn(settings, "sound")); // true

The in operator searches the prototype chain. A direct read also follows that chain. A truthiness check then mixes two questions: whether a value is present and whether that value converts to true. Neither expresses the contract that an imported field must be an own property.

The Object.hasOwn reference explains this distinction: inherited fields are excluded, while own fields count even when their values are null or undefined. The ECMAScript algorithm performs the own-property check after converting its arguments. Our validator below checks the container first rather than relying on that conversion.

Keep Presence Separate from Value Policy

For an optional sound field, use the following contract:

Input stateResult
No own sound propertyDefault to true
Own sound: trueReturn true
Own sound: falseReturn false
Own sound with any other valueReject
Null, array, or primitive containerReject

Save this as sound-setting.mjs:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
export function readSoundSetting(settings) {
  if (settings === null || typeof settings !== "object" ||
      Array.isArray(settings)) {
    throw new TypeError("Expected a settings object");
  }
  if (!Object.hasOwn(settings, "sound")) return true;

  const sound = settings.sound;
  if (typeof sound !== "boolean") {
    throw new TypeError("sound must be a Boolean");
  }
  return sound;
}

An inherited sound is treated as absent under this policy. An own undefined is present and invalid. JSON text cannot directly encode undefined, but callers constructing objects in JavaScript can supply it. The distinction makes the helper’s behavior predictable in both cases.

This helper checks one field; it allows unrelated fields and does not validate an entire settings schema. The input is intended to be ordinary data, such as an object returned by JSON.parse(). Reading an own accessor can execute its getter, and proxies can intercept property operations. This is not an isolation mechanism for arbitrary executable objects.

Avoid Calling a Method on Imported Data

A JSON object can contain a field called hasOwnProperty. Calling that field as a method then fails:

1
2
3
4
5
6
7
8
const imported = JSON.parse('{"hasOwnProperty":0,"sound":false}');
console.log(typeof imported.hasOwnProperty); // number
console.log(Object.hasOwn(imported, "sound")); // true

const bare = Object.create(null);
bare.sound = false;
console.log(typeof bare.hasOwnProperty);     // undefined
console.log(Object.hasOwn(bare, "sound"));   // true

Object.hasOwn() works for both containers because the check is a static method, independent of the input’s fields or prototype. A null-prototype object has no inherited hasOwnProperty method at all.

If an older runtime lacks Object.hasOwn(), the equivalent established call for these checks is Object.prototype.hasOwnProperty.call(settings, "sound"). Check the runtime used by your application before choosing an API. Changing the presence check does not change the separate Boolean validation requirement.

Apply the Default Only After Checking Ownership

Save this as load-settings.mjs beside the validator:

1
2
3
4
5
6
7
8
9
import { readSoundSetting } from "./sound-setting.mjs";

export function loadSoundPreference(text) {
  const settings = JSON.parse(text);
  return readSoundSetting(settings);
}

console.log(loadSoundPreference("{}"));              // true
console.log(loadSoundPreference('{"sound":false}')); // false

Let the caller handle parse and validation errors before applying the setting. Invalid JSON produces a SyntaxError; a valid JSON value with the wrong shape or field type produces a TypeError here.

settings.sound || true would overwrite a valid false preference. settings.sound ?? true preserves false but accepts other invalid values and uses the default for an explicitly supplied null. Neither matches the contract above. Ownership and value validation make the default conditional on absence alone.

Checking ownership also does not make arbitrary copying or merging safe. Keep the validated Boolean as the result instead of forwarding the whole imported object into unrelated configuration code.

Test Missing, Inherited, and Explicit Values

Save this as test-sound-setting.mjs and run node test-sound-setting.mjs:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import assert from "node:assert/strict";
import { readSoundSetting } from "./sound-setting.mjs";

assert.equal(readSoundSetting({}), true);
assert.equal(readSoundSetting({ sound: true }), true);
assert.equal(readSoundSetting({ sound: false }), false);
assert.equal(readSoundSetting(Object.create({ sound: false })), true);
assert.equal(readSoundSetting(Object.create(null)), true);
assert.equal(readSoundSetting(Object.assign(Object.create(null),
                                          { sound: false })), false);
assert.equal(readSoundSetting(JSON.parse(
  '{"hasOwnProperty":0,"sound":false}')), false);

for (const sound of [undefined, null, 0, 1, "false", "", [], {}]) {
  assert.throws(() => readSoundSetting({ sound }), TypeError);
}
for (const input of [null, undefined, false, 1, "{}", [], () => {}]) {
  assert.throws(() => readSoundSetting(input), TypeError);
}
const hidden = Object.defineProperty({}, "sound", { value: false });
assert.equal(readSoundSetting(hidden), false);
console.log("Own-field settings checks passed.");

The non-enumerable example confirms that ownership is independent of enumeration. The inherited example confirms that prototype defaults cannot impersonate explicitly supplied data. Together with false and invalid-value tests, these cases protect the boundary that a truthiness check would erase.