How to Check if an Object Has a Key in JavaScript


How can we check if an object has a specific key in JavaScript?

Suppose we have an object obj created from the following:

obj = { id: 1 }

Check for key using in operator

We can easily use the in operator to check for the existence of a key.

'id' in obj // true

In order to check for the lack of a key, we can use the inverse.

!('id' in obj) // false

Caveat with the in operator

Note that the in operator will check for all object keys, including those in the object’s prototype chain.

We can check an object’s prototype chain and its defined fields using __proto__:

obj.__proto__

This will return an object mapping from a function name to function. We might see something like this:

  • constructor: Æ’ Object()
  • hasOwnProperty: Æ’ hasOwnProperty()
  • isPrototypeOf: Æ’ isPrototypeOf()
  • propertyIsEnumerable: Æ’ propertyIsEnumerable()
  • toLocaleString: Æ’ toLocaleString()
  • toString: Æ’ toString()
  • valueOf: Æ’ valueOf()
  • __defineGetter__: Æ’ __defineGetter__()
  • __defineSetter__: Æ’ __defineSetter__()
  • __lookupGetter__: Æ’ __lookupGetter__()
  • __lookupSetter__: Æ’ __lookupSetter__()

All of these keys also live in the object’s prototype chain as a key.

'constructor' in obj      // true
'toString' in obj         // true
'__lookupSetter__' in obj // true

Check for key using hasOwnProperty()

It’s recommended to use hasOwnProperty() to check for the existence of a key in an object.

This method will check if the key is available on the object directly and does not check the prototype chain.

obj.hasOwnProperty('id')               // true
obj.hasOwnProperty('constructor')      // false
obj.hasOwnProperty('toString')         // false
obj.hasOwnProperty('__lookupSetter__') // false

This method is generally what developers are searching for.

Errors with ESLint’s no-prototype-builtins rule

If we’re using ESLint, we’ll notice that there’s a violation when trying to use hasOwnProperty().

The no-prototype-builtins rule disallows calling some Object.prototype methods directly on object instances.

We’ll get an error like this:

Do not access Object.prototype method 'hasOwnProperty' from target object.

The workaround is to call the method from Object.prototype directly:

Object.prototype.hasOwnProperty.call(obj, 'id');