Check if javascript property exists

JavaScript check if property exists in Object

You might need to determine if an object holds a particular property.

Let’s say we have a user object. Optionally the email property can be set. If not, we want to show a form so the user can fill out their email.

How can we determine if this field exists?

const userOne =  name: 'Chris Bongers', email: 'info@daily-dev-tips.com', >; const userTwo =  name: 'John Do', >;

And to answer that, there are several ways of doing that. Let’s take a look at the three most common ones.

Using hasOwnProperty to see if an object has a property permalink

By using hasOwnProperty we can evaluate if an object has Own property.

Let’s see how it would work on our example data.

console.log(userOne.hasOwnProperty('email')); // Returns: true console.log(userTwo.hasOwnProperty('email')); // Returns: false

That is perfect. But there is a catch to using this method. It only works for Own properties, not extended object properties.

Читайте также:  Grid Layout в CSS3

As you may know, objects come with the toString method, and if we try to check if that exists, it will return false. (While this does exist)

console.log(userOne.toString()); // Returns: [object Object] console.log(userOne.hasOwnProperty('toString')); // Returns false

Using in to see if an object has a property permalink

Another more explicit way of checking if an object has a property is using in .

This one can check in own and inherited properties.

console.log('email' in userOne); // Returns: true console.log('email' in userTwo); // Returns: false console.log('toString' in userOne); // Returns: true

Using undefined to see if an object has a property permalink

The last method is to use an undefined check. This method will work for omitted properties but can cause you headaches if the property exists but has an undefined value.

console.log(userOne.email !== undefined); // Returns: true console.log(userTwo.email !== undefined); // Returns: false console.log(userOne.toString !== undefined); // Returns: true

Now let’s see what happens in the following example:

const userThree =  name: 'Steve Stevenson', email: undefined, >; console.log(userThree.email !== undefined); // Returns: false

The check is acceptable, but it’s not what we might be looking for.

When trying to find out if an object holds a particular property, we need to consider how safe we want to be.

I would generally not recommend using the undefined check.

If you only evaluate Own properties, the hasOwnProperty is a solid solution.

But you might want to be on the safe side and use the in check to determine if an object has a property.

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Источник

3 Ways to Check If an Object Has a Property/Key in JavaScript

Post cover

In this post, you’ll read 3 common ways to check for property or key existence in a JavaScript object.

Note: In the post, I describe property existence checking, which is the same as checking for key existence in an object.

Before I go on, let me recommend something to you.

The path to becoming good at JavaScript isn’t easy. but fortunately with a good teacher you can shortcut.

Take «Modern JavaScript From The Beginning 2.0» course by Brad Traversy to become proficient in JavaScript in just a few weeks. Use the coupon code DMITRI and get your 20% discount!

Table of Contents

Every JavaScript object has a special method object.hasOwnProperty(‘myProp’) that returns a boolean indicating whether object has a property myProp .

In the following example, hasOwnProperty() determines the presence of properties name and realName :

hero.hasOwnProperty(‘name’) returns true because the property name exists in the object hero .

On the other side, hero doesn’t have realName property. Thus hero.hasOwnProperty(‘realName’) returns false — denoting a missing property.

The method name hasOwnProperty() suggests that it looks for the own properties of the object. The own properties are those defined directly upon the object.

This way hasOwnProperty() doesn’t detect the toString — an inherited method from the prototype object:

‘myProp’ in object also determines whether myProp property exists in object .

Let’s use in operator to detect the existence of name and realName in hero object:

‘name’ in hero evaluates to true because hero has a property name .

On the other side, ‘realName’ in hero evaluates to false because hero doesn’t have a property named ‘realName’ .

in operator has a short syntax, and I prefer it over hasOwnProperty() method.

The main difference between hasOwnProperty() method and in operator is that the latter checks within own and inherited properties of the object.

That’s why, in contrast to hasOwnProperty() , the in operator detects that hero object contains the inherited property toString :

3. Comparing with undefined

Accessing a non-existing property from an object results in undefined :

hero.realName evaluates to undefined because realName property is missing.

Now you can see the idea: you can compare with undefined to determine the existence of the property.

hero.name !== undefined evaluates to true , which shows the existence of property.

On the other side, hero.realName !== undefined is false , which indicates that realName is missing.

Comparing with undefined to detect the existence of property is a cheap and dirty approach.

But be aware of false-negatives. If the property exists, but has undefined value (case, however, rarely happening), comparing against undefined evaluates incorrectly to false :

Even if the property name exists (but has undefined value), hero.name !== undefined evaluates to false : which incorrectly indicates a missing property.

There are mainly 3 ways to check if the properties or keys exist in an object.

The first way is to invoke object.hasOwnProperty(propName) . The method returns true if the propName exists inside object , and false otherwise.

hasOwnProperty() searches only within the own properties of the object.

The second approach makes use of propName in object operator. The operator evaluates to true for an existing property, and false otherwise.

in operator looks for properties existence in both own and inherited properties.

Finally, you can simply use object.propName !== undefined and compare against undefined directly.

What’s your preferred way to check for properties existence?

Источник

How to Check if a Property Exists in a JavaScript Object

How to Check if a Property Exists in a JavaScript Object

When you are working with objects in JavaScript, you might need to check if a specific property exists or not.

In this article, I will show you three ways to check if a property exists in a JavaScript object.

How to Use the hasOwnProperty() Method in JavaScript

The hasOwnProperty() method will check if an object contains a direct property and will return true or false if it exists or not.

In this first example, we have an object called developer with three properties:

If we wanted to check if the isEmployed property exists in the developer object, then we can use the hasOwnProperty() method, like this:

developer.hasOwnProperty("isEmployed")

This would return true because the property called isEmployed is a direct property of the developer object.

But what if we tried checking for a property called isPrototypeOf ?

developer.hasOwnProperty("isPrototypeOf")

This would return false because there is no direct property called isPrototypeOf on the developer object. But what do I mean by direct property?

Whenever you create an object in JavaScript, there is a built-in property called a prototype and the value is another object. That object will have its own prototype, and this is know as a prototype chain.

Screen-Shot-2022-04-23-at-6.47.02-PM

Our developer object has access to these other properties, like toString , and this is what is known as an inherited property.

The hasOwnProperty() method will only return true for direct properties and not inherited properties from the prototype chain.

How to Use the in Operator

Unlike the hasOwnProperty() method, the in operator will return true for both direct and inherited properties that exist in the object.

We can modify our earlier example to check if the country property exists in the developer object using the in operator.

This would return true because the country property is a direct property in the developer object.

We can also check if the toString property exists on the developer object or in the prototype chain.

This would return true because the toString property does exist in the prototype chain because it was inherited from the prototype object.

How to Check if a Property Exists in an Object using undefined

If I tried to access a property name in an object that does not exist, then I would get undefined.

For example, if I tried developer.age then the return value would be undefined because the developer object does not have that property name.

We can check if a property exists in the object by checking if property !== undefined .

In this example, it would return true because the name property does exist in the developer object.

Conclusion

If you need to check if a property exists in a JavaScript object, then there are three common ways to do that.

The hasOwnProperty() method will check if an object contains a direct property and will return true or false if it exists or not. The hasOwnProperty() method will only return true for direct properties and not inherited properties from the prototype chain.

Unlike the hasOwnProperty() method, the in operator will return true for both direct and inherited properties that exist in the object or its prototype chain.

Lastly, we can see if a property exists in the object by checking if property !== undefined .

I hope you enjoyed this article and best of luck on your developer journey.

Источник

Оцените статью