JavaScript: Check Property Existence

By Xah Lee. Date: . Last updated: .

Check If a Object Has Own Property

obj.hasOwnProperty(key)

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

〔►see JavaScript: 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 JavaScript: 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 JavaScript: for-in Loop

JS Object Property Topic

  1. JavaScript: Property Overview
  2. JavaScript: Property Key
  3. JavaScript: Property Dot Notation / Bracket Notation
  4. JavaScript: Create/Delete Property
  5. JavaScript: Get Property, Set Property
  6. JavaScript: Check Property Existence
  7. JavaScript: Access Property, List Properties
  8. JavaScript: Property Attributes
  9. JavaScript: Getter/Setter Properties
  10. JavaScript: Property Descriptor
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.