JS: Check Property Existence

By Xah Lee. Date: . Last updated: .

Check If a Object Has Own Property


Return true if object obj has own property key key (string or symbol). Else, false.

[see JS: Object.prototype.hasOwnProperty]

Check If a Property is in Prototype Chain

To check if a property key is in a object obj's prototype chain (including if it's its own property), use one of:

key in obj → return true if property key key is obj's own property or if key is a property of some object in obj's prototype chain. (Both string and symbol keys) Else, false.

[see JS: Symbol Tutorial]

// check if a property is in prototype chain

var o1 = {"p1":1};

// create a object o2, with parent o1
var o2 = Object.create(o1);

o2["p2"] = 2;

console.log("p1" in o2)         // true
console.log("p2" in o2)         // true

// non-existent property
console.log("yyyyy" in o1)         // false
console.log("yyyyy" in o2)         // false

Example with symbol key:

// the “in” operator works with both string and symbol keys

var sy = Symbol();

var ob = {};
ob["st"] = 3; // add a string key
ob[sy] = 4;   // add a symbol key

console.log( "st" in ob ) // true
console.log( sy in ob ) // true

Note: the syntax p in o is not a part of the syntax for (var p in o) {…}. They look the same but don't have the same meaning. [see JS: for-in Loop]

JS Object Property Topic

  1. JS: Property Overview
  2. JS: Property Key
  3. JS: Property Dot Notation / Bracket Notation
  4. JS: Create/Delete Property
  5. JS: Get Property, Set Property
  6. JS: Check Property Existence
  7. JS: Access Property
  8. JS: Property Attributes, writable, enumerable, configurable
  9. JS: Getter/Setter Properties
  10. JS: Property Descriptor
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon