824

I am checking for the existence of an object property with a variable holding the property name in question.

var myObj;
myObj.prop = "exists";
var myProp = "p"+"r"+"o"+"p";

if(myObj.myProp){
    alert("yes, i have that property");
};

This is undefined because it's looking for myObj.myProp but I want it to check for myObj.prop

robinCTS
  • 5,746
  • 14
  • 30
  • 37
Slopeside Creative
  • 8,901
  • 4
  • 17
  • 18
  • 3
    Possibly useful: From a comment by Pablo Cabrera at [NCZOnline](http://www.nczonline.net/blog/2010/07/27/determining-if-an-object-property-exists/): "I think it’s worth to note that if the `hasOwnProperty` method is overwritten, you can rely on the `Object.prototype.hasOwnProperty.call(object, property)`." – HumanInDisguise Apr 07 '15 at 08:45
  • 12
    is https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable a duplicate of this question? how is that? 'checking existence' and 'accessing value' are different things? Please correct me if I am wrong .... – adnan2nd May 10 '18 at 17:14
  • this is not a duplicate. – Jeff Clayton Sep 06 '19 at 20:13
  • @HumanInDisguise comments should not be used to provide resolving advice. Your comment would have been better placed as an answer which contains static quoted advice and a link to its source. Now that @ adnan2d has posted this advice, your comment can be safely deleted. – mickmackusa Jun 09 '21 at 02:05

11 Answers11

1537
var myProp = 'prop';
if(myObj.hasOwnProperty(myProp)){
    alert("yes, i have that property");
}

Or

var myProp = 'prop';
if(myProp in myObj){
    alert("yes, i have that property");
}

Or

if('prop' in myObj){
    alert("yes, i have that property");
}

Note that hasOwnProperty doesn't check for inherited properties, whereas in does. For example 'constructor' in myObj is true, but myObj.hasOwnProperty('constructor') is not.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • 35
    `hasOwnProperty()` is better then `myObj[myProp]` (from other answers) as it works even if the value of `myProp` is 0 – Matt R Oct 26 '12 at 19:48
  • 9
    The "in" operator does not work with strings. e.g. 'length' in 'qqq' will produce an exception. So if you want a general purpose check you need to use hasOwnProperty. – Jacob Jun 19 '14 at 17:55
  • 2
    @Jacob what do you mean when you say 'The "in" operator does not work with strings'? with "in"' operator the left expression must be a string or value that can converts into a string. Yes, you cannot write 'length' in 'qqq' but you cannot write 'qqq'.hasOwnProperty('length') either – Wachburn Jul 21 '15 at 17:18
  • 2
    @Wachburn: `'qqq'.hasOwnProperty('length')` is `true`, you can do that. – gen_Eric Jul 21 '15 at 17:48
  • @MattR what do you mean by "it works even if the value of myProp is 0" ? – gaurav5430 Oct 23 '19 at 05:44
  • 1
    @gaurav5430 I believe what I am referring to is that if `myProp` is 0, the if statement would look like `if (myObj[0])` which if `myObj` has any properties at all, the expresssion would evaluate to `true`. And `myObj[0]` may not be the property you are looking for. – Matt R Oct 26 '19 at 02:14
  • 4
    To avoid breaking eslint `no-prototype-builtins` rule you should use `Object.prototype.hasOwnProperty.call(myObj, myProp)` instead of `myObj.hasOwnProperty(myProp)` – Ilyich Aug 29 '20 at 15:44
  • @RocketHazmat while you *can* indeed do 'qqq'.hasOwn... that does not check if the object qqq has anything. It checks that the anonymous string with value "qqq" has that property, which seems useless since you know at compile time if that is true or not so why would you check that at runtime? I mean you're technically correct but... not sure it holds as an argument against using `in` unless I'm missing something here. – AnorZaken Jul 14 '21 at 10:09
61

You can use hasOwnProperty, but based on the reference you need quotes when using this method:

if (myObj.hasOwnProperty('myProp')) {
    // do something
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

Another way is to use in operator, but you need quotes here as well:

if ('myProp' in myObj) {
    // do something
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in

Adorjan Princz
  • 11,708
  • 3
  • 34
  • 25
  • 6
    That is [**not**](http://jsfiddle.net/s8eegdry/1) how `hasOwnProperty()` is implemented. – canon Jul 09 '15 at 00:59
  • 7
    This is incorrect. By putting quotes around the name myProp, you are no longer referencing the value of myProp, rather you are declaring a new String() of 'myProp' and there is no such property of 'myProp' in myObj. – TriumphST Jun 11 '16 at 23:32
  • 1
    TriumpST: from MDN linked above, "prop - A string or symbol representing a property name or array index (non-symbols will be coerced to strings)." – Ben Creasy Oct 18 '17 at 18:22
  • This is correct. If you don't want to use a variable, but just if a specific 'myProp' is present, you need the quotes. – Katinka Hesselink Oct 24 '18 at 09:51
  • @KatinkaHesselink: Your comment is misleading. The question was "How to check if object property exists with a variable holding the property name?" – Herbert Van-Vliet Jan 08 '19 at 10:36
  • just used in in Chrome 80 with double quotes, worked for me. :/ – Adesso Mar 26 '20 at 17:14
  • 1
    'hasOwnProperty' is not equivalent to using the 'in' operator, as Rocket Hazmat's answer explains. – Max Barraclough Jun 30 '20 at 17:27
26

Thank you for everyone's assistance and pushing to get rid of the eval statement. Variables needed to be in brackets, not dot notation. This works and is clean, proper code.

Each of these are variables: appChoice, underI, underObstr.

if(typeof tData.tonicdata[appChoice][underI][underObstr] !== "undefined"){
    //enter code here
}
Slopeside Creative
  • 8,901
  • 4
  • 17
  • 18
  • 1
    This looks like a problem to me. If `tData.tonicdata[appChoice]` results in a value that doesn't have a property/index that matches `underI`, then this will result in an `TypeError` being thrown. – Ynot Mar 26 '19 at 22:37
  • 2
    Despite your intentions with your initial post, you actually asked a different question than the one for which you provided this answer. You wanted to check the existence of a property, you don't mention anything about how to access it. Which makes this answer unrelated to the actual question. – Forage Apr 11 '19 at 11:34
24

For own property :

var loan = { amount: 150 };
if(Object.prototype.hasOwnProperty.call(loan, "amount")) 
{ 
   //will execute
}

Note: using Object.prototype.hasOwnProperty is better than loan.hasOwnProperty(..), in case a custom hasOwnProperty is defined in the prototype chain (which is not the case here), like

var foo = {
      hasOwnProperty: function() {
        return false;
      },
      bar: 'Here be dragons'
    };

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

To include inherited properties in the finding use the in operator: (but you must place an object at the right side of 'in', primitive values will throw error, e.g. 'length' in 'home' will throw error, but 'length' in new String('home') won't)

const yoshi = { skulk: true };
const hattori = { sneak: true };
const kuma = { creep: true };
if ("skulk" in yoshi) 
    console.log("Yoshi can skulk");

if (!("sneak" in yoshi)) 
    console.log("Yoshi cannot sneak");

if (!("creep" in yoshi)) 
    console.log("Yoshi cannot creep");

Object.setPrototypeOf(yoshi, hattori);

if ("sneak" in yoshi)
    console.log("Yoshi can now sneak");
if (!("creep" in hattori))
    console.log("Hattori cannot creep");

Object.setPrototypeOf(hattori, kuma);

if ("creep" in hattori)
    console.log("Hattori can now creep");
if ("creep" in yoshi)
    console.log("Yoshi can also creep");

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in

Note: One may be tempted to use typeof and [ ] property accessor as the following code which doesn't work always ...

var loan = { amount: 150 };

loan.installment = undefined;

if("installment" in loan) // correct
{
    // will execute
}

if(typeof loan["installment"] !== "undefined") // incorrect
{
    // will not execute
}
adnan2nd
  • 2,083
  • 20
  • 16
13

A much more secure way to check if property exists on the object is to use empty object or object prototype to call hasOwnProperty()

var foo = {
  hasOwnProperty: function() {
    return false;
  },
  bar: 'Here be dragons'
};

foo.hasOwnProperty('bar'); // always returns false

// Use another Object's hasOwnProperty and call it with 'this' set to foo
({}).hasOwnProperty.call(foo, 'bar'); // true

// It's also possible to use the hasOwnProperty property from the Object
// prototype for this purpose
Object.prototype.hasOwnProperty.call(foo, 'bar'); // true

Reference from MDN Web Docs - Object.prototype.hasOwnProperty()

skmasq
  • 4,470
  • 6
  • 42
  • 77
  • 5
    If you are incorporating JavaScript that might do something evil like override `hasOwnProperty`, no amount of guards like this will make your code safe or secure. – meustrus Dec 31 '18 at 20:16
  • @meustrus I know where you coming from, but from business perspective it is highly possible to receive that an inexperienced developer would use this property name, which not necessarily mean their are doing something evil intentionally. – skmasq Jan 11 '19 at 18:16
11

there are much simpler solutions and I don't see any answer to your actual question:

"it's looking for myObj.myProp but I want it to check for myObj.prop"

  1. to obtain a property value from a variable, use bracket notation.
  2. to test that property for truthy values, use optional chaining
  3. to return a boolean, use double-not / bang-bang / (!!)
  4. use the in operator if you are certain you have an object and only want to check for the existence of the property (true even if prop value is undefined). or perhaps combine with nullish coalescing operator ?? to avoid errors being thrown.

var nothing = undefined;
var obj = {prop:"hello world"}
var myProp = "prop";

consolelog( 1,()=> obj.myProp); // obj does not have a "myProp"
consolelog( 2,()=> obj[myProp]); // brackets works
consolelog( 3,()=> nothing[myProp]); // throws if not an object
consolelog( 4,()=> obj?.[myProp]); // optional chaining very nice ⭐️⭐️⭐️⭐️⭐️
consolelog( 5,()=> nothing?.[myProp]); // optional chaining avoids throwing
consolelog( 6,()=> nothing?.[nothing]); // even here it is error-safe
consolelog( 7,()=> !!obj?.[myProp]); // double-not yields true
consolelog( 8,()=> !!nothing?.[myProp]); // false because undefined
consolelog( 9,()=> myProp in obj); // in operator works
consolelog(10,()=> myProp in nothing); // throws if not an object
consolelog(11,()=> myProp in (nothing ?? {})); // safe from throwing
consolelog(12,()=> myProp in {prop:undefined}); // true (prop key exists even though its value undefined)

// beware of 'hasOwnProperty' pitfalls
// it can't detect inherited properties and 'hasOwnProperty' is itself inherited
// also comparatively verbose
consolelog(13,()=> obj.hasOwnProperty("hasOwnProperty")); // DANGER: it yields false 
consolelog(14,()=> nothing.hasOwnProperty("hasOwnProperty")); // throws when undefined
obj.hasOwnProperty = ()=>true; // someone could overwrite it
consolelog(15,()=> obj.hasOwnProperty(nothing)); // DANGER: the foolish overwrite will now always return true
consolelog(16,()=> Object.prototype.hasOwnProperty.call(obj,"hasOwnProperty")); // explain?!
consolelog(17,()=> Object.hasOwn(obj,"hasOwnProperty")); // explain?!

function consolelog(num,myTest){
    try{
    console.log(num,myTest());
    }
    catch(e){
    console.log(num,'throws',e.message);
    }
}
bristweb
  • 948
  • 14
  • 14
6

You can use hasOwnProperty() as well as in operator.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Simran Kaur
  • 1,103
  • 5
  • 24
  • 40
5

Using the new Object.hasOwn method is another alternative and it's intention is to replace the Object.hasOwnProperty method.

This static method returns true if the specified object has the indicated property as its own property or false if the property is inherited or does not exist on that object.

Please not that you must check the Browser compatibility table carefully before using this in production since it's still considered an experimental technology and is not fully supported yet by all browsers (soon to be though)

    var myObj = {};
    myObj.myProp = "exists";

    if (Object.hasOwn(myObj, 'myProp')){
        alert("yes, i have that property");
    }

More about Object.hasOwn - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn

Object.hasOwn browser compatibility - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn#browser_compatibility

Ran Turner
  • 14,906
  • 5
  • 47
  • 53
2

Several ways to check if an object property exists.

const dog = { name: "Spot" }

if (dog.name) console.log("Yay 1"); // Prints.
if (dog.sex) console.log("Yay 2"); // Doesn't print. 

if ("name" in dog) console.log("Yay 3"); // Prints.
if ("sex" in dog) console.log("Yay 4"); // Doesn't print.

if (dog.hasOwnProperty("name")) console.log("Yay 5"); // Prints.
if (dog.hasOwnProperty("sex")) console.log("Yay 6"); // Doesn't print, but prints undefined.
daCoda
  • 3,583
  • 5
  • 33
  • 38
0

Working for me.

if (typeof receviedData?.d?.heartbeat_interval != "undefined") {
}
Murat Çakmak
  • 151
  • 2
  • 7
-1

In the answers I didn't see the !! truthiness check.

if (!!myObj.myProp) //Do something

fp007
  • 412
  • 1
  • 4
  • 18
  • Can you please link me to some documentation on this `!!` operator? I have searched google high and low and I cannot find it anywhere, I can only find the `!` operator – supafiya Jul 06 '21 at 00:40
  • 1
    This is just a double negation pattern. https://stackoverflow.com/questions/10467475/double-negation-in-javascript-what-is-the-purpose – elpezganzo Oct 04 '21 at 15:36
  • 1
    You didn’t see it here because it’s wrong. This is not a property-existence check, but a truthiness check. – Sebastian Simon Mar 01 '22 at 11:08