1805

How do I check if an object has a specific property in JavaScript?

Consider:

x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
    //Do this
}

Is that the best way to do it?

Let Me Tink About It
  • 15,156
  • 21
  • 98
  • 207
sheats
  • 33,062
  • 15
  • 45
  • 44
  • 31
    I wrote a jsperf test with everyone's answers to see which is fastest: http://jsperf.com/dictionary-contains-key – styfle Mar 10 '16 at 16:36
  • ('propertyName' in Object) ? 'property is there' : 'property is not there' – Mohan Ram Oct 05 '18 at 09:08
  • 2
    @styfle thanks for the jsperf test. `in` and `hasOwnProperty` came out *way* slower than the others for me (98% slower). I'm not surprised about `hasOwnProperty` being slower but I am surprised about `in`. – evanrmurphy Nov 16 '18 at 20:16
  • 3
    There’s a new stage 3 proposal, [`Object.hasOwn`](//github.com/tc39/proposal-accessible-object-hasownproperty), which addresses a few of the problems of `Object.prototype.hasOwnProperty`. – Sebastian Simon Aug 19 '21 at 22:19

32 Answers32

1682

2022 UPDATE

Object.hasOwn()

Object.hasOwn() is recommended over Object.hasOwnProperty() because it works for objects created using Object.create(null) and with objects that have overridden the inherited hasOwnProperty() method. While it is possible to workaround these problems by calling Object.prototype.hasOwnProperty() on an external object, Object.hasOwn() is more intuitive.

Example

const object1 = {
  prop: 'exists'
};

console.log(Object.hasOwn(object1, 'prop'));
// expected output: true

Original answer

I'm really confused by the answers that have been given - most of them are just outright incorrect. Of course you can have object properties that have undefined, null, or false values. So simply reducing the property check to typeof this[property] or, even worse, x.key will give you completely misleading results.

It depends on what you're looking for. If you want to know if an object physically contains a property (and it is not coming from somewhere up on the prototype chain) then object.hasOwnProperty is the way to go. All modern browsers support it. (It was missing in older versions of Safari - 2.0.1 and older - but those versions of the browser are rarely used any more.)

If what you're looking for is if an object has a property on it that is iterable (when you iterate over the properties of the object, it will appear) then doing: prop in object will give you your desired effect.

Since using hasOwnProperty is probably what you want, and considering that you may want a fallback method, I present to you the following solution:

var obj = {
    a: undefined,
    b: null,
    c: false
};

// a, b, c all found
for ( var prop in obj ) {
    document.writeln( "Object1: " + prop );
}

function Class(){
    this.a = undefined;
    this.b = null;
    this.c = false;
}

Class.prototype = {
    a: undefined,
    b: true,
    c: true,
    d: true,
    e: true
};

var obj2 = new Class();

// a, b, c, d, e found
for ( var prop in obj2 ) {
    document.writeln( "Object2: " + prop );
}

function hasOwnProperty(obj, prop) {
    var proto = obj.__proto__ || obj.constructor.prototype;
    return (prop in obj) &&
        (!(prop in proto) || proto[prop] !== obj[prop]);
}

if ( Object.prototype.hasOwnProperty ) {
    var hasOwnProperty = function(obj, prop) {
        return obj.hasOwnProperty(prop);
    }
}

// a, b, c found in modern browsers
// b, c found in Safari 2.0.1 and older
for ( var prop in obj2 ) {
    if ( hasOwnProperty(obj2, prop) ) {
        document.writeln( "Object2 w/ hasOwn: " + prop );
    }
}

The above is a working, cross-browser, solution to hasOwnProperty(), with one caveat: It is unable to distinguish between cases where an identical property is on the prototype and on the instance - it just assumes that it's coming from the prototype. You could shift it to be more lenient or strict, based upon your situation, but at the very least this should be more helpful.

Christopher Peisert
  • 21,862
  • 3
  • 86
  • 117
John Resig
  • 35,521
  • 3
  • 29
  • 19
  • 5
    @grantwparks If you are building a simple slider plugin and want to check for the existence of an options item, then this might be more than needed indeed. You can just do something like `var w = opts.w || 100;`. But if you are onto a library kind of something, you may need to go a little bit farther at some parts. – Halil Özgür Feb 22 '11 at 16:28
  • @kralco626: Yes, nowadays I feel it's pretty safe to go with hasOwnProperty() – but for truly safe cross-browser solution, go with John's. – Jacob Jan 10 '12 at 13:28
  • What about _temporary_ changing `__proto__` to null? Simple impl: `function hasOwnProperty(obj, prop) { var temp = obj.__proto__; obj.__proto__ = null; var ret = prop in obj; obj.__proto__ = temp; return ret; }` (Case with `obj.constructor.prototype` should be added). – average Joe Dec 17 '12 at 10:06
  • 2
    @Kasztan `__proto__` is non-standard and doesn't work in some older browsers. And even with the recent addition of `Object.getPrototypeOf` the standard says you still can't change the prototype of an existing object. – Matt Browne Feb 25 '13 at 19:11
  • 1
    John Resig's answers does not seem to work in IE8, see it fail in this live demo http://jsbin.com/tovaburefeva/1/edit?js,output . I think it's because `hasOwnProperty() "is not supported on host objects for Internet Explorer 8 and below"` see http://msdn.microsoft.com/en-us/library/ie/328kyd6z(v=vs.94).aspx and also http://stackoverflow.com/questions/8157700/object-has-no-hasownproperty-method-i-e-its-undefined-ie8 – Adriano Oct 14 '14 at 10:43
  • 15
    A `for(prop in object)` loop iterates only enumerable properties. However, `prop in object` checks whether `object` has the property `prop` somewhere in the prototypical chain, independently on whether it's enumerable or not. – Oriol Jan 05 '16 at 23:27
  • As a side note to functions declared inside if's, this works in all modern browsers I'm aware of, but it is not supported by PhantomJS. – Aardvark Sep 30 '16 at 19:17
  • Since ECMA Script Version 6 embeds the Reflect function that is the preferred way to go. It has a 'has()' and a 'get()' which makes it very easy to create a wrapper to get Safe-Arguments. Not all browsers may support this functionality (not in IE and Opera), but hat will change soon. Use the ECMA 'use version 6' to ensure a correct Script version. – Harm Dec 19 '16 at 10:46
  • 1
    Word of warning: don't use `in` check on primitives. – S.D. Sep 02 '20 at 20:08
  • why can't you just pass the property in through the subscript operator and check if it returns a falsy value? if you're looking for a property name that isn't shared in the prototype chain, then this is too much work – Wassim Katbey Feb 17 '22 at 18:02
  • 1
    In 2022 you can use Object.hasOwn(). He doesn't seem to be active anymore, but anyone looking for JavaScript books, this guy has written the best imo. I think he uses Manning for a publisher, which is a company that I really like. – JΛYDΞV Jun 20 '22 at 10:50
  • Note that `hasOwn` is not supported by Safari <15.4 which, as of 2022, still comprises a fair number of users (~10% of Safari users on our particular site). `core-js` will polyfill it, but `core-js-pure` *does not*. – Andrew Dec 02 '22 at 10:42
321

With Underscore.js or (even better) Lodash:

_.has(x, 'key');

Which calls Object.prototype.hasOwnProperty, but (a) is shorter to type, and (b) uses "a safe reference to hasOwnProperty" (i.e. it works even if hasOwnProperty is overwritten).

In particular, Lodash defines _.has as:

function has(object, key) {
  return object ? hasOwnProperty.call(object, key) : false;
}
// hasOwnProperty = Object.prototype.hasOwnProperty
xxx
  • 1,153
  • 1
  • 11
  • 23
Brian M. Hunt
  • 81,008
  • 74
  • 230
  • 343
  • 73
    I would guess it's because "add this library" is seldom a popular solution even when the question is about complex DOM manipulation and the answer is "go use jQuery". – Winfield Trail Sep 04 '14 at 19:15
  • 13
    I see your point, @sudowned, thanks. Incidentally, if one were averse to including the entire lodash library one could compile subcomponents or `npm install lodash.has` which exposes an npm module with just a `has` function that compiles down to 175 bytes when minified. It is also insightful to look at the `lodash.has/index.js` to see how a very popular and trusted library works. – Brian M. Hunt Sep 04 '14 at 19:41
  • 10
    and `lodash`'s versions works with this: `.has(undefined, 'someKey') => false` while `underscore` returns `undefined` – Brad Parks Sep 10 '14 at 11:06
  • Thanks @BradParks -- I had not actually looked at the documentation for the `underscore` version, so I am sure this might be a useful point for someone reading this. – Brian M. Hunt Sep 10 '14 at 13:29
  • 1
    Thanks @brian-m-hunt I'm already including lodash, started searching around before I should have been RTFM. – Paul J Mar 16 '15 at 22:18
  • 4
    I don't believe using a library is an acceptable answer because the question asks "in JavaScript" not "using a JavaScript library." – Dave Apr 19 '16 at 19:59
  • 21
    To everyone whining about adding `lodash` as "yet another" dependency: it's a fairly common (if not THE most common) library for this sort of thing. Have fun reinventing the wheel. – Priidu Neemre Nov 18 '16 at 12:37
  • 19
    Even if you want to reinvent the wheel, checking out existing wheels is not a bad idea. – AturSams Apr 25 '17 at 11:53
  • 2
    Also, the OP may not have even known about it. So saying 'in JavaScript' or 'with JQuery' doesn't mean they are not open to new libraries they may not have known existed and were just trying to use basic Javascript or Jquery because they thought that was all they had at their disposal for this. But, the selected answer mentioning using 'hasOwnProperty' is the simplest way to do this. – Tyler Dahle Jun 22 '17 at 15:31
  • 5
    For the love of God use Lodash or whatever other library is available until JS sorts out its pretty, petty little head. At least if you go that route you are off-loading the ridiculous amount of hoop-jumping for browser compatibility. Problem: solved. Move on. – Damien Roche Oct 10 '18 at 06:25
  • 2
    The beauty with _.has is that you can use dot notation to check for deeply nested attributes, eg _.has(myObject, 'a.b.c'); – omarjebari Jun 30 '20 at 12:52
218

You can use this (but read the warning below):

var x = {
  'key': 1
};

if ('key' in x) {
  console.log('has');
}

But be warned: 'constructor' in x will return true even if x is an empty object - same for 'toString' in x, and many others. It's better to use Object.hasOwn(x, 'key').

joe
  • 3,752
  • 1
  • 32
  • 41
Whisher
  • 31,320
  • 32
  • 120
  • 201
  • 19
    Just to note, it works with 'objects' in narrow sense, so declared as {} or created using constructor, it doesn't accept arrays or primitives. Not that the OP has required it, but some other answers present techniques that are more broad (work with arrays, strings etc.) – Danubian Sailor Aug 27 '14 at 12:22
  • 1
    @РСТȢѸФХѾЦЧШЩЪЫЬѢѤЮѦѪѨѬѠѺѮѰѲѴ thanks for pointing that out (the accepted answer does not go into details on why one should use the `in` operator or not. Also note that the `in` operator has excellent browser support `IE 5.5+, Chrome 1.0+, Firefox 1.0+, Safari 3.0+` http://stackoverflow.com/questions/2920765/javascript-in-operator-compatibility – Adriano Oct 15 '14 at 07:42
  • 4
    Operator `in` also checks against prototype properties, while `hasOwnProperty` iterates user-defined properties only. Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in – adi518 Jul 09 '16 at 11:57
  • 3
    `'key' in x` **_do_** work with arrays. Proof: http://stackoverflow.com/questions/33592385/if-0-in-array-is-this-even-legal – CosmoMyzrailGorynych Jan 05 '17 at 01:54
146

Note: the following is nowadays largely obsolete thanks to strict mode, and hasOwnProperty. The correct solution is to use strict mode and to check for the presence of a property using obj.hasOwnProperty. This answer predates both these things, at least as widely implemented (yes, it is that old). Take the following as a historical note.


Bear in mind that undefined is (unfortunately) not a reserved word in JavaScript if you’re not using strict mode. Therefore, someone (someone else, obviously) could have the grand idea of redefining it, breaking your code.

A more robust method is therefore the following:

if (typeof(x.attribute) !== 'undefined')

On the flip side, this method is much more verbose and also slower. :-/

A common alternative is to ensure that undefined is actually undefined, e.g. by putting the code into a function which accepts an additional parameter, called undefined, that isn’t passed a value. To ensure that it’s not passed a value, you could just call it yourself immediately, e.g.:

(function (undefined) {
    … your code …
    if (x.attribute !== undefined)
        … mode code …
})();
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 6
    Just curious, since `void 0` is defined to return the canonical `undefined`, could one do `x.attribute !== void 0`? – Brian M. Hunt Feb 01 '13 at 17:01
  • 1
    Brian: I'm no expert, but that sure seems like a clever way to get it right. – Christopher Smith Feb 25 '13 at 22:29
  • 41
    If the famous 'someone else' have redefined what undefined is, I think the best course of action would be to rewrite THAT code. – Oskar Holmkratz May 18 '13 at 18:00
  • `undefined = (function () {}()); if (a.attribute !== undefined) 'foo';` – Joe Simmons Sep 30 '13 at 01:40
  • 3
    The best to have a solid undefined var, is to work within a closure, and have an unmatched function signature: `(function (undefined) { // undefined is actually undefined here })();` – bgusach Oct 15 '13 at 10:20
  • Since ES5 strict mode, you cannot redefine undefined anymore, but you do have to remember to turn on the strict mode. :) Also, this answer does not test whether an object has some property, but test whether the property is undefined (which includes both existing and non-existing props). –  Dec 09 '16 at 20:50
  • @BrianM.Hunt your suggestion with `x.attribute !== void 0` (or `void(0)`) works great in my test. – evanrmurphy Nov 16 '18 at 20:19
  • 1
    @evanrmurphy Don't use that, it's seriously outdated (see note at the beginning of my answer). – Konrad Rudolph Nov 17 '18 at 13:19
61
if (x.key !== undefined)

Armin Ronacher seems to have already beat me to it, but:

Object.prototype.hasOwnProperty = function(property) {
    return this[property] !== undefined;
};

x = {'key': 1};

if (x.hasOwnProperty('key')) {
    alert('have key!');
}

if (!x.hasOwnProperty('bar')) {
    alert('no bar!');
}

A safer, but slower solution, as pointed out by Konrad Rudolph and Armin Ronacher would be:

Object.prototype.hasOwnProperty = function(property) {
    return typeof this[property] !== 'undefined';
};
Community
  • 1
  • 1
enobrev
  • 22,314
  • 7
  • 42
  • 53
  • 2
    I don't think that's good enough. `x.hasOwnProperty('toString') === true;` – Joe Simmons Sep 28 '13 at 07:28
  • Not asking to disagree, but to understand. Is there any point where x.hasOwnProperty would return anything besides a boolean true or false? If not, the code as posted should work every time. I suppose maybe if the method were overridden, but then, relying on the result would never be reliable unless you know the overriding method. – enobrev Sep 29 '13 at 15:47
  • 1
    I think we have a miscommunication. I mean that using your method, it would say that 'toString' is its own property, but it isn't. – Joe Simmons Sep 30 '13 at 01:38
  • 3
    `Object.prototype` already has a built-in, correct `hasOwnProperty`. Overwriting it with an incorrect implementation (1. Properties can have the value `undefined`, 2. This will give false positives for inherited properties) is just a hideously bad idea. Incorrect answers can and should be deleted. I don't know if you could do that back in Sep '08 [when you saw Resig's answer](http://stackoverflow.com/questions/135448/how-do-i-check-if-an-object-has-a-property-in-javascript/135475#comment35250_136411), so commenting to suggest doing it now. – T.J. Crowder Sep 18 '16 at 08:10
44

Considering the following object in Javascript

const x = {key: 1};

You can use the in operator to check if the property exists on an object:

console.log("key" in x);

You can also loop through all the properties of the object using a for - in loop, and then check for the specific property:

for (const prop in x) {
    if (prop === "key") {
        //Do something
    }
}

You must consider if this object property is enumerable or not, because non-enumerable properties will not show up in a for-in loop. Also, if the enumerable property is shadowing a non-enumerable property of the prototype, it will not show up in Internet Explorer 8 and earlier.

If you’d like a list of all instance properties, whether enumerable or not, you can use

Object.getOwnPropertyNames(x);

This will return an array of names of all properties that exist on an object.

Reflections provide methods that can be used to interact with Javascript objects. The static Reflect.has() method works like the in operator as a function.

console.log(Reflect.has(x, 'key'));
// expected output: true

console.log(Reflect.has(x, 'key2'));
// expected output: false

console.log(Reflect.has(object1, 'toString'));
// expected output: true

Finally, you can use the typeof operator to directly check the data type of the object property:

if (typeof x.key === "undefined") {
    console.log("undefined");
}

If the property does not exist on the object, it will return the string undefined. Else it will return the appropriate property type. However, note that this is not always a valid way of checking if an object has a property or not, because you could have a property that is set to undefined, in which case, using typeof x.key would still return true (even though the key is still in the object).

Similarly, you can check if a property exists by comparing directly to the undefined Javascript property

if (x.key === undefined) {
    console.log("undefined");
}

This should work unless key was specifically set to undefined on the x object

goonerify
  • 1,668
  • 25
  • 27
33

Let's cut through some confusion here. First, let's simplify by assuming hasOwnProperty already exists; this is true of the vast majority of current browsers in use.

hasOwnProperty returns true if the attribute name that is passed to it has been added to the object. It is entirely independent of the actual value assigned to it which may be exactly undefined.

Hence:

var o = {}
o.x = undefined

var a = o.hasOwnProperty('x')  // a is true
var b = o.x === undefined // b is also true

However:

var o = {}

var a = o.hasOwnProperty('x')  // a is now false
var b = o.x === undefined // b is still true

The problem is what happens when an object in the prototype chain has an attribute with the value of undefined? hasOwnProperty will be false for it, and so will !== undefined. Yet, for..in will still list it in the enumeration.

The bottom line is there is no cross-browser way (since Internet Explorer doesn't expose __prototype__) to determine that a specific identifier has not been attached to an object or anything in its prototype chain.

Aliaksandr Sushkevich
  • 11,550
  • 7
  • 37
  • 44
AnthonyWJones
  • 187,081
  • 35
  • 232
  • 306
32

If you are searching for a property, then "no". You want:

if ('prop' in obj) { }

In general, you should not care whether or not the property comes from the prototype or the object.

However, because you used 'key' in your sample code, it looks like you are treating the object as a hash, in which case your answer would make sense. All of the hashes keys would be properties in the object, and you avoid the extra properties contributed by the prototype.

John Resig's answer was very comprehensive, but I thought it wasn't clear. Especially with when to use "'prop' in obj".

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Gerard ONeill
  • 3,914
  • 39
  • 25
  • 1
    Note that the `in` operator has excellent browser support `IE 5.5+, Chrome 1.0+, Firefox 1.0+, Safari 3.0+` http://stackoverflow.com/questions/2920765/javascript-in-operator-compatibility – Adriano Oct 15 '14 at 07:38
  • As pointed out in another comment regarding using the `in` operator: "it works with 'objects' in narrow sense, so declared as {} or created using constructor, it doesn't accept arrays or primitives. Not that the OP has required it, but some other answers present techniques that are more broad (work with arrays, strings etc.)" – Adriano Oct 15 '14 at 07:44
  • 1
    Commenting cause I've been downvoted twice without comment. But I still like my answer. Perhaps whoever did so wanted a 'comprehensive' answer for all ways to test for all types of properties.. But my answer is conceptual and for that, succinct. Re: Adrien Be, an unenumerable property is one that isn't meant for general user scope, so conceptually 'in' is fine ;) – Gerard ONeill Nov 27 '17 at 17:36
25

For testing simple objects, use:

if (obj[x] !== undefined)

If you don't know what object type it is, use:

if (obj.hasOwnProperty(x))

All other options are slower...

Details

A performance evaluation of 100,000,000 cycles under Node.js to the five options suggested by others here:

function hasKey1(k,o) { return (x in obj); }
function hasKey2(k,o) { return (obj[x]); }
function hasKey3(k,o) { return (obj[x] !== undefined); }
function hasKey4(k,o) { return (typeof(obj[x]) !== 'undefined'); }
function hasKey5(k,o) { return (obj.hasOwnProperty(x)); }

The evaluation tells us that unless we specifically want to check the object's prototype chain as well as the object itself, we should not use the common form:

if (X in Obj)...

It is between 2 to 6 times slower depending on the use case

hasKey1 execution time: 4.51 s
hasKey2 execution time: 0.90 s
hasKey3 execution time: 0.76 s
hasKey4 execution time: 0.93 s
hasKey5 execution time: 2.15 s

Bottom line, if your Obj is not necessarily a simple object and you wish to avoid checking the object's prototype chain and to ensure x is owned by Obj directly, use if (obj.hasOwnProperty(x))....

Otherwise, when using a simple object and not being worried about the object's prototype chain, using if (typeof(obj[x]) !== 'undefined')... is the safest and fastest way.

If you use a simple object as a hash table and never do anything kinky, I would use if (obj[x])... as I find it much more readable.

davidhadas
  • 2,333
  • 21
  • 17
  • Your middle paragraph implies that "IF (x in obj)" is good for checking the prototype chain, but your second to last paragraph implies that it checks the chain and is faster. So is "syntax" the only reason to use (x in obj)? – Gerard ONeill Mar 03 '23 at 17:39
  • "x in obj" is the only evaluated option that checks the prototype chain – davidhadas Aug 07 '23 at 05:33
20

Yes it is :) I think you can also do Object.prototype.hasOwnProperty.call(x, 'key') which should also work if x has a property called hasOwnProperty :)

But that tests for own properties. If you want to check if it has an property that may also be inhered you can use typeof x.foo != 'undefined'.

Armin Ronacher
  • 31,998
  • 13
  • 65
  • 69
18
if(x.hasOwnProperty("key")){
  // …
}

because

if(x.key){
  // …
}

fails if x.key is falsy (for example, x.key === "").

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
17

You can also use the ES6 Reflect object:

x = {'key': 1};
Reflect.has( x, 'key'); // returns true

Documentation on MDN for Reflect.has can be found here.

The static Reflect.has() method works like the in operator as a function.

Wilt
  • 41,477
  • 12
  • 152
  • 203
17

Do not do this object.hasOwnProperty(key)). It's really bad because these methods may be shadowed by properties on the object in question - consider { hasOwnProperty: false } - or, the object may be a null object (Object.create(null)).

The best way is to do Object.prototype.hasOwnProperty.call(object, key) or:

const has = Object.prototype.hasOwnProperty; // Cache the lookup once, in module scope.
console.log(has.call(object, key));
/* Or */
import has from 'has'; // https://www.npmjs.com/package/has
console.log(has(object, key));
jprdl
  • 3
  • 2
Abdullah Danyal
  • 1,106
  • 1
  • 9
  • 25
  • 6
    I agree with this method and it should be the accepted answer as it is the safest way while maintaining performance! https://eslint.org/docs/rules/no-prototype-builtins says "For example, it would be unsafe for a webserver to parse JSON input from a client and call hasOwnProperty directly on the resulting object, because a malicious client could send a JSON value like {"hasOwnProperty": 1} and cause the server to crash." – Arman Oct 06 '19 at 23:24
13

OK, it looks like I had the right answer unless if you don't want inherited properties:

if (x.hasOwnProperty('key'))

Here are some other options to include inherited properties:

if (x.key) // Quick and dirty, but it does the same thing as below.

if (x.key !== undefined)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sheats
  • 33,062
  • 15
  • 45
  • 44
10

Another relatively simple way is using Object.keys. This returns an array which means you get all of the features of an array.

var noInfo = {};
var info = {something: 'data'};

Object.keys(noInfo).length //returns 0 or false
Object.keys(info).length //returns 1 or true

Although we are in a world with great browser support. Because this question is so old I thought I'd add this: This is safe to use as of JavaScript v1.8.5.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jamie Hutber
  • 26,790
  • 46
  • 179
  • 291
  • Right but what if you wanted to know if info had a property with the name someotherthing? Which is think is what OP is looking for. – Victorio Berra Oct 26 '15 at 16:40
  • 3
    Then you would do `Object.keys(info).indexOf('someotherthing') !== -1` – hippietrail Jun 15 '16 at 04:18
  • What is *"JS v1.8.5"*? "JavaScript v1.8.5"*? It doesn't appear to match any [ECMAScript](https://en.wikipedia.org/wiki/ECMAScript) version (version 8 was released in 2017). [jQuery](https://en.wikipedia.org/wiki/JQuery) 1.8 was released in 2012. – Peter Mortensen Oct 06 '20 at 16:24
  • OK, [JavaScript 1.8.5](https://developer.mozilla.org/en-US/docs/Archive/Web/JavaScript/New_in_JavaScript/1.8.5) was released in 2011 with [Firefox 4](https://en.wikipedia.org/wiki/Firefox_early_version_history#Firefox_4) (2011-03-22). The first version of [ECMAScript 5](https://en.wikipedia.org/wiki/ECMAScript#5th_Edition) (linked to) is from 2009. – Peter Mortensen Oct 06 '20 at 16:53
  • 2
    @hippietrail I think `Object.keys(info).includes('something')` is more ergonomic. – arcanemachine Sep 04 '22 at 19:59
  • Example is given [here](https://stackoverflow.com/a/66332561/7765316) – majurageerthan Nov 13 '22 at 06:34
10

JavaScript is now evolving and growing as it now has good and even efficient ways to check it.

Here are some easy ways to check if object has a particular property:

  1. Using hasOwnProperty()
const hero = {
  name: 'Batman'
};

hero.hasOwnProperty('name');     // => true
hero.hasOwnProperty('realName'); // => false
  1. Using keyword/operator in
const hero = {
  name: 'Batman'
};

'name' in hero;     // => true
'realName' in hero; // => false
  1. Comparing with undefined keyword
const hero = {
  name: 'Batman'
};

hero.name;     // => 'Batman'
hero.realName; // => undefined

// So consider this
hero.realName == undefined // => true (which means property does not exists in object)
hero.name == undefined // => false (which means that property exists in object)

For more information, check here.

Blessing
  • 2,450
  • 15
  • 22
8

hasOwnProperty "can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain."

So most probably, for what seems by your question, you don't want to use hasOwnProperty, which determines if the property exists as attached directly to the object itself,.

If you want to determine if the property exists in the prototype chain, you may want to use it like:

if (prop in object) { // Do something }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
rogopag
  • 101
  • 1
  • 3
5

You can use the following approaches-

var obj = {a:1}
console.log('a' in obj)               // 1
console.log(obj.hasOwnProperty('a'))  // 2
console.log(Boolean(obj.a))         // 3

The difference between the following approaches are as follows-

  1. In the first and third approach we are not just searching in object but its prototypal chain too. If the object does not have the property, but the property is present in its prototype chain it is going to give true.

var obj = {
    a: 2,
    __proto__ : {b: 2}
}

console.log('b' in obj)
console.log(Boolean(obj.b))
  1. The second approach will check only for its own properties. Example -

var obj = {
    a: 2,
    __proto__ : {b: 2}
}

console.log(obj.hasOwnProperty('b'))
  1. The difference between the first and the third is if there is a property which has value undefined the third approach is going to give false while first will give true.

var obj = {
    b : undefined
}

console.log(Boolean(obj.b))
console.log('b' in obj);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Komal Bansal
  • 789
  • 2
  • 7
  • 20
5

Given myObject object and “myKey” as key name:

Object.keys(myObject).includes('myKey')

or

myObject.hasOwnProperty('myKey')

or

typeof myObject.myKey !== 'undefined'

The last was widely used, but (as pointed out in other answers and comments) it could also match on keys deriving from Object prototype.

Marco Balestra
  • 167
  • 2
  • 6
5

Now with ECMAScript22 we can use hasOwn instead of hasOwnProperty (Because this feature has pitfalls )

Object.hasOwn(obj, propKey)
nassim miled
  • 581
  • 1
  • 6
  • 18
4

Performance

Today 2020.12.17 I perform tests on MacOs HighSierra 10.13.6 on Chrome v87, Safari v13.1.2 and Firefox v83 for chosen solutions.

Results

I compare only solutions A-F because they give valid result for all cased used in snippet in details section. For all browsers

  • solution based on in (A) is fast or fastest
  • solution (E) is fastest for chrome for big objects and fastest for firefox for small arrays if key not exists
  • solution (F) is fastest (~ >10x than other solutions) for small arrays
  • solutions (D,E) are quite fast
  • solution based on losash has (B) is slowest

enter image description here

Details

I perform 4 tests cases:

  • when object has 10 fields and searched key exists - you can run it HERE
  • when object has 10 fields and searched key not exists - you can run it HERE
  • when object has 10000 fields and searched key exists - you can run it HERE
  • when object has 10000 fields and searched key exists - you can run it HERE

Below snippet presents differences between solutions A B C D E F G H I J K

// SO https://stackoverflow.com/q/135448/860099


// src: https://stackoverflow.com/a/14664748/860099
function A(x) {
  return 'key' in x
}

// src: https://stackoverflow.com/a/11315692/860099
function B(x) {
  return _.has(x, 'key')
}

// src: https://stackoverflow.com/a/40266120/860099
function C(x) {
  return Reflect.has( x, 'key')
}

// src: https://stackoverflow.com/q/135448/860099
function D(x) {
  return x.hasOwnProperty('key')
}

// src: https://stackoverflow.com/a/11315692/860099
function E(x) {
  return Object.prototype.hasOwnProperty.call(x, 'key')
}

// src: https://stackoverflow.com/a/136411/860099
function F(x) {
  function hasOwnProperty(obj, prop) {
      var proto = obj.__proto__ || obj.constructor.prototype;
      return (prop in obj) &&
          (!(prop in proto) || proto[prop] !== obj[prop]);
  }
  return hasOwnProperty(x,'key')
}

// src: https://stackoverflow.com/a/135568/860099
function G(x) {
  return typeof(x.key) !== 'undefined'
}

// src: https://stackoverflow.com/a/22740939/860099
function H(x) {
  return x.key !== undefined
}

// src: https://stackoverflow.com/a/38332171/860099
function I(x) {
  return !!x.key
}

// src: https://stackoverflow.com/a/41184688/860099
function J(x) {
  return !!x['key']
}

// src: https://stackoverflow.com/a/54196605/860099
function K(x) {
  return Boolean(x.key)
}


// --------------------
// TEST
// --------------------

let x1 = {'key': 1};
let x2 = {'key': "1"};
let x3 = {'key': true};
let x4 = {'key': []};
let x5 = {'key': {}};
let x6 = {'key': ()=>{}};
let x7 = {'key': ''};
let x8 = {'key': 0};
let x9 = {'key': false};
let x10= {'key': undefined};
let x11= {'nokey': 1};



let b= x=> x ? 1:0;

console.log('  1 2 3 4 5 6 7 8 9 10 11');

[A,B,C,D,E,F,G,H,I,J,K ].map(f=> {  
  console.log(
    `${f.name} ${b(f(x1))} ${b(f(x2))} ${b(f(x3))} ${b(f(x4))} ${b(f(x5))} ${b(f(x6))} ${b(f(x7))} ${b(f(x8))} ${b(f(x9))} ${b(f(x10))}  ${b(f(x11))} `
  )})
  
console.log('\nLegend: Columns (cases)');
console.log('1.  key = 1 ');
console.log('2.  key = "1" ');
console.log('3.  key = true ');
console.log('4.  key = [] ');
console.log('5.  key = {} ');
console.log('6.  key = ()=>{} ');
console.log('7.  key = "" ');
console.log('8.  key = 0 ');
console.log('9.  key = false ');
console.log('10. key = undefined ');
console.log('11. no-key ');
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"> </script>
  
This shippet only presents functions used in performance tests - it not perform tests itself!

And here are example results for chrome

enter image description here

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
3

Here is another option for a specific case. :)

If you want to test for a member on an object and want to know if it has been set to something other than:

  • ''
  • false
  • null
  • undefined
  • 0 ...

then you can use:

var foo = {};
foo.bar = "Yes, this is a proper value!";
if (!!foo.bar) {
    // member is set, do something
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
arkod
  • 1,973
  • 1
  • 20
  • 20
3

some easier and short options depending on the specific use case:

  1. to check if the property exists, regardless of value, use the in operator ("a" in b)
  2. to check a property value from a variable, use bracket notation (obj[v])
  3. to check a property value as truthy, use optional chaining (?.)
  4. to check a property value boolean, use double-not / bang-bang / (!!)
  5. to set a default value for null / undefined check, use nullish coalescing operator (??)
  6. to set a default value for falsey value check, use short-circuit logical OR operator (||)

run the code snippet to see results:

let obj1 = {prop:undefined};
console.log(1,"prop" in obj1);
console.log(1,obj1?.prop);

let obj2 = undefined;
//console.log(2,"prop" in obj2); would throw because obj2 undefined
console.log(2,"prop" in (obj2 ?? {}))
console.log(2,obj2?.prop);

let obj3 = {prop:false};
console.log(3,"prop" in obj3);
console.log(3,!!obj3?.prop);

let obj4 = {prop:null};
let look = "prop"
console.log(4,"prop" in obj4);
console.log(4,obj4?.[look]);

let obj5 = {prop:true};
console.log(5,"prop" in obj5);
console.log(5,obj5?.prop === true);

let obj6 = {otherProp:true};
look = "otherProp"
console.log(6,"prop" in obj6);
console.log(6,obj6.look); //should have used bracket notation

let obj7 = {prop:""};
console.log(7,"prop" in obj7);
console.log(7,obj7?.prop || "empty"); 

I see very few instances where hasOwn is used properly, especially given its inheritance issues

bristweb
  • 948
  • 14
  • 14
2

An ECMAScript 6 solution with reflection. Create a wrapper like:

/**
Gets an argument from array or object.
The possible outcome:
- If the key exists the value is returned.
- If no key exists the default value is returned.
- If no default value is specified an empty string is returned.
@param obj    The object or array to be searched.
@param key    The name of the property or key.
@param defVal Optional default version of the command-line parameter [default ""]
@return The default value in case of an error else the found parameter.
*/
function getSafeReflectArg( obj, key, defVal) {
   "use strict";
   var retVal = (typeof defVal === 'undefined' ? "" : defVal);
   if ( Reflect.has( obj, key) ) {
       return Reflect.get( obj, key);
   }
   return retVal;
}  // getSafeReflectArg
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Harm
  • 787
  • 7
  • 11
  • Is this the best way to do it when you're targeting >= ES6? – hippietrail Aug 30 '17 at 04:36
  • 1
    Imho it is the shortest and most simple answer, but maybe not the fastest in execution code. But speed is not an issue (anymore). – Harm Aug 31 '17 at 14:20
  • Why post [the same answer](https://stackoverflow.com/a/40266120/1697459) twice? You could just upvote the existing one...? – Wilt Nov 19 '20 at 19:15
2

There is a method, "hasOwnProperty", that exists on an object, but it's not recommended to call this method directly, because it might be sometimes that the object is null or some property exist on the object like: { hasOwnProperty: false }

So a better way would be:

// Good
var obj = {"bar": "here bar desc"}
console.log(Object.prototype.hasOwnProperty.call(obj, "bar"));

// Best
const has = Object.prototype.hasOwnProperty; // Cache the lookup once, in module scope.
console.log(has.call(obj, "bar"));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
vikram jeet singh
  • 3,416
  • 2
  • 21
  • 22
2

Showing how to use this answer

const object= {key1: 'data', key2: 'data2'};

Object.keys(object).includes('key1') //returns true

We can use indexOf as well, I prefer includes

majurageerthan
  • 2,169
  • 3
  • 17
  • 30
2

I had a hard time understanding the difference between hasOwn and hasOwnProperty even though there are 30 answers trying to explain this. Here's a runnable snippet, so you can see for yourself how it behaves.

const object1 = {
  prop: 'exists'
};
object1.property1 = 42;

// the following as you might expect output true
console.log(object1.hasOwnProperty('property1'));
console.log(Object.hasOwn(object1,"prop"));
console.log(Object.hasOwn(object1,"property1"));

// the following might surpize you, they output false
console.log(Object.hasOwnProperty(object1,"prop"));
console.log(Object.hasOwnProperty(object1,"property1"));

// the following as you rightfully expect output false
console.log(object1.hasOwnProperty('toString'));
console.log(Object.hasOwn(object1,"toString"));
console.log(Object.hasOwnProperty(object1,"toString"));

console.log(object1.hasOwnProperty('hasOwnProperty'));
console.log(Object.hasOwn(object1,"hasOwnProperty"));
console.log(Object.hasOwnProperty(object1,"hasOwnProperty"));
Tom Rutchik
  • 1,183
  • 1
  • 12
  • 15
1

You need to use the method object.hasOwnProperty(property). It returns true if the object has the property and false if the object doesn't.

Zissouu
  • 924
  • 2
  • 10
  • 17
John Anisere
  • 513
  • 1
  • 3
  • 13
1

The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).

const object1 = {};
object1.property1 = 42;

console.log(object1.hasOwnProperty('property1'));
// expected output: true

console.log(object1.hasOwnProperty('toString'));
// expected output: false

console.log(object1.hasOwnProperty('hasOwnProperty'));
// expected output: false

Know more

MD SHAYON
  • 7,001
  • 45
  • 38
0

Don't over-complicate things when you can do:

var isProperty =  (objectname.keyname || "") ? true : false;

It Is simple and clear for most cases...

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alex
  • 272
  • 2
  • 10
  • The most simplest one is var isProperty = !!objectname.keyname; – John Jan 24 '19 at 07:04
  • 1
    If the object is as follows `const objectName = { keyname: false };` it should return true, since `keyname` is a property of `objectname`. But since the value is false it would return false with this logic. – Wilt Oct 17 '19 at 08:53
0

A Better approach for iterating on object's own properties:

If you want to iterate on object's properties without using hasOwnProperty() check, use for(let key of Object.keys(stud)){} method:

for(let key of Object.keys(stud)){
  console.log(key); // will only log object's Own properties
}

full Example and comparison with for-in with hasOwnProperty()

function Student() {
  this.name = "nitin";
}

Student.prototype = {
  grade: 'A'
}

let stud = new Student();

// for-in approach
for(let key in stud){
  if(stud.hasOwnProperty(key)){
    console.log(key); // only outputs "name"
  }
} 

//Object.keys() approach
for(let key of Object.keys(stud)){
  console.log(key);
}
Nitin Jadhav
  • 6,495
  • 1
  • 46
  • 48
0

x?.key returns 1 if x.key exists, otherwise undefined