856

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

4
  • 3
    Possibly useful: From a comment by Pablo Cabrera at NCZOnline: "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)." Commented Apr 7, 2015 at 8:45
  • 12
    is stackoverflow.com/questions/4244896/… a duplicate of this question? how is that? 'checking existence' and 'accessing value' are different things? Please correct me if I am wrong .... Commented May 10, 2018 at 17:14
  • this is not a duplicate. Commented Sep 6, 2019 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. Commented Jun 9, 2021 at 2:05

11 Answers 11

1595
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.

Sign up to request clarification or add additional context in comments.

10 Comments

hasOwnProperty() is better then myObj[myProp] (from other answers) as it works even if the value of myProp is 0
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 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: 'qqq'.hasOwnProperty('length') is true, you can do that.
To avoid breaking eslint no-prototype-builtins rule you should use Object.prototype.hasOwnProperty.call(myObj, myProp) instead of myObj.hasOwnProperty(myProp)
|
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

7 Comments

That is not how hasOwnProperty() is implemented.
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.
TriumpST: from MDN linked above, "prop - A string or symbol representing a property name or array index (non-symbols will be coerced to strings)."
This is correct. If you don't want to use a variable, but just if a specific 'myProp' is present, you need the quotes.
'hasOwnProperty' is not equivalent to using the 'in' operator, as Rocket Hazmat's answer explains.
|
27

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
}

2 Comments

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.
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.
23

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
}

Comments

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()

2 Comments

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 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.
12

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);
    }
}

Comments

5

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

4 Comments

All of this ^ is why I hate javascript
@pwaterz don't hate the player 🙄
'hasOwnProperty' is not equivalent to using the 'in' operator, as Rocket Hazmat's answer explains.
maybe you could try to explain when does using either option don't really matters, but accepted answer is pretty clear
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

Comments

3

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.

Comments

2

Working for me.

if (typeof receviedData?.d?.heartbeat_interval != "undefined") {
}

Comments

-1

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

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

3 Comments

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
This is just a double negation pattern. stackoverflow.com/questions/10467475/…
You didn’t see it here because it’s wrong. This is not a property-existence check, but a truthiness check.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.