Use the in
keyword:
"key" in object
which returns true
or false
, depending if the object, or anything in its prototype chain, has that property.
You can also use object.hasOwnProperty("key")
, which will only be true
if the object has key
as a property of itself, not its prototype. Example:
var object = {};
"toString" in object; // true
object.hasOwnProperty("toString"); // false
Note (as per @dandavis's comment) that if object
has a custom property called hasOwnProperty
, this gets thwarted; to work around this, use hasOwnProperty.call(object, "key")
. Example:
var a = {hasOwnProperty: Boolean};
a.hasOwnProperty('name'); // true
hasOwnProperty.call(a, 'name'); // false