How to check if a property exists in an object in JavaScript

Hasownproperty() method, in operator, comparison with undefined.

JavaScript provides several ways to check if a property exists in an object. You can choose one of the following methods to check the presence of a property:

  • hasOwnProperty() method
  • in operator

The hasOwnProperty() method is part of the object's prototype and returns a boolean value ( true or false ) indicating whether the object has the specified property as its own property .

Let us say you have the following food object:

The following example uses the hasOwnProperty() method to check if the fries property exists in the food object:

If the property doesn't exist in the object, the hasOwnProperty() method returns false as shown below:

Note that the hasOwnProperty() method only checks the presence of the specified property in the object's own properties. The own properties are those defined directly on the object.

If the property is a part of the object's prototype, it is not considered as an object's own property. For example, the hasOwnProperty() method doesn't detect the toString property because it is inherited from the object's prototype:

The in operator is another way to check the presence of a property in an object in JavaScript. It returns true if the property exists in an object. Otherwise, it returns false .

Let us use the in operator to look for the cake property in the food object:

Unlike the hasOwnProperty() method, the in operator looks for the existence of a property within the own properties and also in the inherited properties of an object.

For example, contrary to hasOwnProperty() , the in operator detects that the inherited toString property exists in the food object:

If you try to access a non-existing property from an object, the returned value is undefined :

The food.rice evaluates to undefined because the food object doesn't contain the rice property.

By using this logic, you can compare the property with the undefined to check if the property exists in an object:

However, if the object contains a property that has undefined value, comparing it with undefined will incorrectly evaluate to false :

As you can see above, even though the job property exists (but has undefined value), user.job !== undefined evaluates to false conveying a false impression that the property doesn't exist.

We learned about 3 different ways to check if an object contains a specific property.

  • The hasOwnProperty() method checks the existence of a property within the own properties of the object.
  • The in operator looks for the property in both own properties and inherited properties of an object.
  • Finally, you can compare the property value with the undefined to check if it exists. You should use this method only when you're sure that the property value is not undefined .

If you are not concerned about the object inherited properties, the in operator is the most suitable method to check the existence of a property. It has a short and concise syntax.

✌️ Like this article? Follow me on Twitter and LinkedIn . You can also subscribe to RSS Feed .

You might also like...

  • Get the length of a Map in JavaScript
  • Delete an element from a Map in JavaScript
  • Get the first element of a Map in JavaScript
  • Get an element from a Map using JavaScript
  • Update an element in a Map using JavaScript
  • Add an element to a Map in JavaScript

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.

  • JavaScript, Node.js & Spring Boot
  • In-depth tutorials
  • Super-handy protips
  • Cool stuff around the web
  • 1-click unsubscribe
  • No spam, free-forever!

Home » 3 Ways to Check If a Property Exists in an Object

3 Ways to Check If a Property Exists in an Object

Summary : in this tutorial, you will learn how to check if a property exists in an object.

JavaScript provides you with three common ways to check if a property exists in an object:

  • Use the hasOwnProperty() method.
  • Use the in operator.
  • Compare property with undefined .

Use the hasOwnProperty() method

The JavaScript Object.prototype has the method hasOwnProperty() that returns true if a property exists in an object:

The following example declares a person object:

And the following uses the hasOwnProperty() method to check if the firstName property exists in the person object:

However, the age property does not exist in the person object, therefore, the following code returns false :

Note that the hasOwnProperty() looks for the property in the own properties of the object.

For example, all objects inherit the toString property of the Object , the hasOwnProperty() method does not detect it as a property:

Use the in operator

The in operator returns true if a property exists in an object. If a property does not exist in the object, it returns false .

The following example uses the in operator to check if the firstName and age properties exist in the person object:

Unlike the hasOwnProperty() method, the in operator looks for the property in both own properties and inherited properties of the object.

The following example uses the in operator to check if the toString property exists in the person object. It returns true because the toString is an inherited property of the person object.

Comparing the property with undefined

When you access a non-existing property of an object, you will get undefined . Therefore, you can compare the property with the undefined to check if a property exists in an object:

If an object has a property whose value is undefined , then comparing the property with undefined will return an incorrect result. For example:

In this example, the age property does exist in the person object. However, its initial value is undefined . Therefore, comparing the person.age with undefined returns false , which is not expected.

  • Use the hasOwnProperty() method to check if an property exists in the own properties of an object.
  • Use the in operator to check if a property exists in both own properties and inherited properties of an object.
  • Compare the property with undefined to check if a property exists only when you are sure that the initial value of the property is not undefined .

How to Check if a Property Exists in a JavaScript Object

Jessica Wilkins

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.

Here is the basic syntax:

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:

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 ?

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.

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.

I am a musician and a programmer.

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

GuidingCode

How to Fix the Error “Cannot Set Headers After They are Sent to the Client” in JavaScript?

How to Fix the “Type 'Null' Is Not Assignable to Type 'String'”?

How to Fix “Type ‘Null’ Is Not Assignable to Type ‘String’” in TypeScript?

How to fix Java Package Does Not Exist

How to Fix the Java “Package Does Not Exist” Error?

Recent posts.

javascript assign if property exists

How to Fix “ReferenceError: Variable Is Not Defined” in JavaScript?

  • WooCommerce
  • Webpack warning

How to Conditionally Add a Property or Member to an Object in JavaScript?

' src=

In JavaScript, we add properties or members to objects dynamically to make your code concise and readable. You should read this article if you don’t know how to add a member to an object conditionally. Keep reading. 🔎

In JavaScript, objects are a fundamental data structure that allows developers to store and manipulate data as key-value pairs. Objects can be used to represent complex data structures and provide a way to organize related data together. One of the most common tasks when working with objects in JavaScript is to conditionally add a member to an object based on specific criteria.

We can add a member to an object by using different techniques such as the ternary operator, if statement , spread operator, Object.assign() , and logical And operator. Using these techniques, you can write concise and readable code in JavaScript. Before we solve the mystery of how to add members conditionally, we first have to understand the concept of objects and members in JavaScript. 

So without any further delay, dive deep into the article.

Table of Contents

What are objects and members in javascript, method 1: using the ternary operator, method 2: using the if statement, method 3: using the logical and operator, method 4: using the object.assign() method, method 5: using the spread operator.

An object is a group of related data and functions represented in JavaScript as key-value pairs. Both properties and methods can be found in an object. A property is a value attached to an object, whereas a method is a function that may be used on an object to carry out an operation or return a result.

An object in JavaScript is defined using curly braces {} and can contain zero or more properties, each of which is a key-value pair separated by a colon : . A string used to identify a property is used as the key . At the same time, the value can be any valid JavaScript expression, including other objects , arrays , functions , and primitive data types (such as strings , numbers , and booleans ). 

Let’s use a straightforward example to clarify this idea:

Different Ways to Conditionally Add a Property or Member to an Object in JavaScript

JavaScript has several ways to add a member to an object conditionally. Here are some of them:

  • Using the ternary operator.
  • Using the if statement.
  • Using the logical And operator.
  • Using the Object.assign() method.
  • Using the spread operator.

The ternary operator is just like an if-else statement in JavaScript. It is often used to assign a value to a variable based on a condition. In some cases, the ternary operator can make code more concise and easier to read, especially when the if-else statement is simple and only has two possible outcomes. 

We can use the ternary operator to add a member to an object conditionally. We can understand how its works with the help of a simple example:

In JavaScript, the if statement is a control flow statement that allows you to execute a code block if a specified condition is true . The general syntax of the if statement is as follows:

Optionally, you can add an else block to the if statement, which will be executed if the condition is false . The general syntax for an if-else statement is as follows:

We can use an if statement to add a member to an object conditionally. Let’s understand its works with the help of this simple example:

The logical And operator (&&) is a binary operator in JavaScript that returns true if both operands are true and otherwise false. We can use JavaScript’s logical And (&&) operator to add a member to an object conditionally.

The general syntax for this technique is:

Here, obj is the name of the Object you want to add a property to, propertyName is the name of a property that already exists on the Object, and value is the value you want to assign to the newProperty .

The logical And operator checks whether the value of propertyName is true. If it is, the expression on the operator’s right-hand side is evaluated. This expression assigns a new property newProperty, to the obj Object, with the value Value .

If the value of propertyName is false , the logical And operator short-circuits and returns false without evaluating the expression on the right-hand side. This ensures that the new property is added only if the existing property is true .

Let’s understand it with the help of a simple example:

In JavaScript, Object.assign() is a built-in method that allows you to copy the values of all enumerable properties from one or more source objects to a target object. The syntax for Object.assign() is as follows:

We can also use the Object.assign method to add a member to an object conditionally.  Let’s understand the working of Object.assign() with the help of a simple example:

In JavaScript, the spread operator (…) is an operator that allows you to expand an iterable object, such as an array or a string, into individual elements. The spread operator can be used in various ways, including passing arguments to functions , merging arrays or objects , and creating copies of arrays or objects .

JavaScript’s spread operator can be combined with the ternary operator to conditionally add a member to an object. Here’s an example to understand the working of a spread operator:

In JavaScript, you can conditionally add a member to an object using the ternary operator, spread operator, Object.assign() , if statement, or logical And operator. These techniques allow you to add a new property to an object based on some condition or set of conditions. Using these methods, you can write concise and readable code and add properties to objects dynamically.

The ternary operator can conditionally add a property to an object and is a concise way to create an if-else statement. The spread operator can copy an existing object and add new properties simultaneously, using object literal syntax. The logical And operator can conditionally add a property to an object based on whether an existing property is true.

These techniques can be helpful when you need to dynamically add a property to an object based on some condition that may or may not be met at runtime. 

If you found this article helpful, don’t forget to share it.

' src=

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

Related Posts

How to Remove the First Element of an Array in JavaScript

How to Fix “ReferenceError: RegeneratorRuntime is Not Defined” in JavaScript?

How to Run or Call Executable (EXE) From JavaScript?

How to Convert Int to Float in JavaScript?

SyntaxError: Cannot Use Import Statement Outside a Module node.js javascript

How to Fix SyntaxError: Cannot Use Import Statement Outside a Module?

How to Check if a String is a Number in JavaScript

How to Check if a String is a Number in JavaScript?

Home

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

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.

Table of Contents

1. hasownproperty() method, 2. in operator, 3. comparing with undefined.

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 :

Open the demo.

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 :

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?

Like the post? Please share!

Dmitri Pavlutin

About Dmitri Pavlutin

Popular posts.

javascript assign if property exists

How to conditionally add a property to an object in JavaScript self.__wrap_n=self.__wrap_n||(self.CSS&&CSS.supports("text-wrap","balance")?1:2);self.__wrap_b=(r,n,e)=>{e=e||document.querySelector(`[data-br="${r}"]`);let o=e.parentElement,l=u=>e.style.maxWidth=u+"px";e.style.maxWidth="";let s,i=o.clientWidth,p=o.clientHeight,a=i/2-.25,d=i+.5;if(i){for(l(a),a=Math.max(e.scrollWidth,a);a+1 {self.__wrap_b(0,+e.dataset.brr,e)})).observe(o)};self.__wrap_n!=1&&self.__wrap_b(":R4p4sm:",1)

javascript assign if property exists

Kris Lachance

Head of Growth

What is Basedash?

Sign up ->

October 30, 2023

Conditionally adding a property to an object in JavaScript can streamline object creation and ensure only relevant data is included. Engineers can achieve this with simple checks and modern JavaScript syntax to keep objects lean and maintainable.

Understand the basics of object manipulation

Objects in JavaScript are mutable, meaning properties can be added, modified, or deleted after an object is created. Here's a simple object for reference:

Use the if statement for conditional addition

An if statement is the most straightforward way to conditionally add a property:

Employ logical operators for inline conditioning

Logical operators like && (AND) can add properties without an explicit if block:

Take advantage of the ternary operator

The ternary operator provides a concise way to conditionally add properties:

Delete unwanted properties

If a property is conditionally added and later deemed unnecessary, the delete keyword helps:

Use the spread operator for conditional properties

ES6 introduced the spread operator, which is handy for conditionally adding properties:

Imagine the time you'd save if you never had to build another internal tool, write a SQL report, or manage another admin panel again. Basedash is built by internal tool builders, for internal tool builders. Our mission is to change the way developers work, so you can focus on building your product.

Learn more about Basedash

Book a demo

javascript assign if property exists

Implement Object.assign for dynamic properties

Object.assign can also be used for conditional additions:

Utilize functions for complex conditions

When dealing with complex conditions, a function can help keep code clean:

Adopt the nullish coalescing operator for defaults

The nullish coalescing operator ( ?? ) can set default property values when a conditionally added property is null or undefined :

Consider the optional chaining operator for nested objects

For deeply nested objects, optional chaining ( ?. ) prevents errors when conditionally adding properties to undefined nested objects:

Embrace functional programming with immutable patterns

To avoid side-effects, use immutable patterns by creating a new object each time:

Leverage ES2020 optional chaining with assignment

ES2020 allows for optional chaining combined with assignment to add properties only if the nested object exists:

By following these techniques, you can add properties to JavaScript objects conditionally, leading to more robust and flexible code. Whether for a simple feature toggle or a complex state-dependent structure, these patterns ensure that objects contain only the necessary data at any given time.

Click to keep reading

Ship faster, worry less with Basedash

You're busy enough with product work to be weighed down building, maintaining, scoping and developing internal apps and admin panels. Forget all of that, and give your team the admin panel that you don't have to build. Launch in less time than it takes to run a standup.

Sign up for free

javascript assign if property exists

Dashboards and charts

Edit data, create records, oversee how your product is running without the need to build or manage custom software.

ADMIN PANEL

Sql composer with ai.

Screenshot of a users table in a database. The interface is very data-dense with information.

Related posts

javascript assign if property exists

How to Remove Characters from a String in JavaScript

Jeremy Sarchet

javascript assign if property exists

How to Sort Strings in JavaScript

javascript assign if property exists

How to Remove Spaces from a String in JavaScript

javascript assign if property exists

Detecting Prime Numbers in JavaScript

Robert Cooper

javascript assign if property exists

How to Parse Boolean Values in JavaScript

javascript assign if property exists

How to Remove a Substring from a String in JavaScript

All JavaScript guides

Check if object has a specific property in JavaScript

You might need to check if a property exists in an object in case:

  • Validate the input data and avoid errors when accessing undefined properties.
  • Filter out the inherited properties and only work with the direct own properties.
  • Perform different actions based on the presence or absence of a property in an object.

There are different ways to check if a property exists in an object in JavaScript, depending on your use case and preference. Here are some of the common methods:

  • Using optional chaining and compare directly with undefined
  • Using hasOwnProperty() or Object.hasOwn()

Using in operator

Using lodash _.has(), using optional chaining.

If your primary concern is checking whether a property exists in an object (regardless of its value being null or undefined ), optional chaining alone is often sufficient.

Optional chaining handles the case where intermediate properties are null or undefined , gracefully returning undefined without throwing an error.

Using hasOwnProperty()

If you specifically want to check whether a property is directly defined on the object (not inherited from its prototype chain), you may still use hasOwnProperty() .

Optional chaining does not distinguish between own properties and inherited properties.

But be careful when the object may not have the hasOwnProperty method itself, or when the method may have been overridden by a custom function. Suppose we have an object foo that is created with Object.create(null) , which means it does not inherit from Object.prototype . If we try to use the hasOwnProperty() method, we will get an error:

In this case you can use Object.prototype.hasOwnProperty.call() method or Object.hasOwn() :

Using Object.hasOwn()

The new method Object.hasOwn() is a static method that returns true if the specified object has the specified property as its own property, and false otherwise. It is intended as a replacement for Object.prototype.hasOwnProperty() , which has some drawbacks and limitations.

If an object is created using Object.create(null) , it does not inherit from Object.prototype , so it does not have the hasOwnProperty() method. In this case, you can use Object.hasOwn() to check for properties, but not hasOwnProperty() .

When an object overrides the inherited hasOwnProperty() method. In this case, the hasOwnProperty() method may not work as expected, but Object.hasOwn() will still work correctly.

It is recommended to use Object.hasOwn() over hasOwnProperty() as it is more reliable and intuitive.

The difference between hasOwnProperty() and in operator is that hasOwnProperty() only checks if the object itself has the property, while in operator checks if the property exists in the object or its prototype chain.

Lodash _.has() is a method that checks if an object has a direct property with a given path. It is similar to the native JavaScript Object.hasOwn() method, checks only for direct properties, ignoring inherited ones.

It’s convenient for checking nested properties using dot notation _.has(obj, 'x.y.z') , useful for validating input data and avoiding errors when accessing undefined properties.

You might also like

DEV Community

DEV Community

Chris Bongers

Posted on Jul 5, 2022 • Originally published at daily-dev-tips.com

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?

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

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

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

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

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)

Using in to see if an object has a property

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

This one can check in own and inherited properties.

Using undefined to see if an object has a property

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.

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

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, and let's connect!

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

Top comments (17)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

peerreynders profile image

  • Joined Feb 29, 2020

Note that starting with ES2022 Object.prototype.hasOwnProperty() has been "replaced" with Object.hasOwn() :

javascript assign if property exists

Object.hasOwn() - JavaScript | MDN

The Object.hasOwn() static method returns true if the specified object has the indicated property as its own property. If the property is inherited, or does not exist, the method returns false.

favicon

"JavaScript does not protect the property name hasOwnProperty ; an object that has a property with this name may return incorrect results…

The recommended way to overcome this problem is to instead use Object.hasOwn() (in browsers that support it). Other alternatives include using an external hasOwnProperty ".

For more details see: TC39 Proposal: Accessible Object.prototype.hasOwnProperty()

There even is an ESLint rule concerning this no-prototype-builtins .

To some degree this demonstrates that it is dangerous in JavaScript to think of objects as objects in the class-based object-oriented sense because there is no guarantee that every JavaScript object will have a prototype and therefore that Object will be in its prototype chain.

dailydevtips1 profile image

  • Location Cape Town, South Africa
  • Work Solution Architect at Daily Dev Tips
  • Joined Apr 20, 2020

Oh nice addition Peer, Missed that one on TC39, but great to see this adoption as it makes total sense.

supportic profile image

  • Joined Oct 27, 2019

You could also do if(userOne["email"]) but I would not recommend to check like this userOne.email !== undefined because what if the object in general does not exist?

means: When userOne does not exist e.g. you forget to pass parameter in a function call, then (undefined).email !== undefined will evaluate not into false or true

=> skip if condition

A fix for that though would be to check if the object exist and if not, assign an empty object to it. options = options ?? {} if (options.switch !== undefined) can now resolve in true or false.

what if the object in general does not exist?

As suggested in another comment optional chaining will work just fine here.

Yeah that's why I mentioned the undefined check to be the least favorite one of all. It get's messy and very prone to cause headaches later on.

bacloud22 profile image

  • Joined Jan 17, 2022

I really like ensuring JavaScript safety by JavaScript built-in environment (browser, node..) and what the language has to offer itself. No typescript, no build systems...

I think it doesn't really make code complex not is it hard to achieve. With good discipline and attention I think the developer would have even more control on his code.

Thanks for the article

Sometimes we tend to overcomplicate for no reason. Plain JavaScript can handle a lot of things for us that actually might even work quicker.

jonrandy profile image

  • Location Bangkok 🇹🇭
  • Joined Jun 1, 2018

You could also check for the existence of the property name in Object.keys(obj) . Again, this only checks the objects own properties

Ah yes, indeed another way of checking for own properties.

iamhectorsosa profile image

  • Location Prague, Czech Republic
  • Work Webscope.io
  • Joined Mar 21, 2021

Great article! I'll add into this using Optional chaining . It helps narrowing down your code when using TypeScript a ton. Of course, also very useful while writing plain JavaScript too.

Optional changing can be a real life-saver when it comes to determining this indeed.

moopet profile image

  • Location Scotland
  • Education Something something cybernetics
  • Pronouns They/them
  • Work Full-stack agency person
  • Joined Aug 29, 2017

You have a typo in your conclusion where you say

the safe side and use the on check to

but you mean "in".

Thanks Ben! Noticed and adjusted it 💖

hnazmul profile image

  • Email [email protected]
  • Location Shylhet,Bangladesh
  • Work Full-Stack Web developer. at Sarit inst.
  • Joined Jan 25, 2021

Great man.. want more tips like this from you..

Let's do some more hands-on tips 💪

imiahazel profile image

  • Location UAE
  • Joined Aug 4, 2021

Thanks for the snippets. These are perfect additions to my coding toolbox.

Awesome Imia 💖

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

rudolfolah profile image

React Router has merged with Remix, should you use a different router?

Rudolf Olah - May 17

abhayradadiya_59 profile image

Understanding Node.js: A Comprehensive Guide

Abhay Radadiya - May 17

marcconci profile image

10 Essential Questions to Ask When Starting with NumPy Data Manipulation

Marcos - May 17

ramunarasinga profile image

How I fixed this Next.js error: Refused to load the script because it violate Content Security Policy directive

Ramu Narasinga - May 16

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

  • Fundamentals
  • All Articles

DWD logo

How to check if an element exists in JavaScript (with examples)

In JavaScript, to check if an element exists or not, you need to access it first. You can use one the following methods to access DOM elements:

🎧 Debugging Jam

Calling all coders in need of a rhythm boost! Tune in to our 24/7 Lofi Coding Radio on YouTube, and let's code to the beat – subscribe for the ultimate coding groove!" Let the bug-hunting begin! 🎵💻🚀

24/7 lofi music radio banner, showing a young man working at his computer on a rainy autmn night with hot drink on the desk.

  • document.getElementById()
  • document.getElementByClassName()
  • document.querySelector()
  • document.querySelectorAll()

Whenever you access a web page, the web browser parses the HTML code and populates a DOM tree of all the elements on the page. It also makes the DOM available to your JavaScript code via the  DOM API . 

And the document object is the entry to the DOM API.

Woman thinking

Psssst! Do you want to learn web development in 2023?

Pixel question mark

  • How to become a web developer when you have no degree
  • How to learn to code without a technical background
  • How much do web developers make in the US?

In these four methods, the first two methods return a single DOM element ( Element ) if the element exists. Otherwise, they return null .

So to check if the element exists in the DOM, you need to check the returned value.

The method document.getElementById() takes a case-sensitive string argument and returns the element whose  id  property matches the specified string. 

If the element doesn’t exist, we’ll get a null value.

Please note the argument you pass to getElementById() is case-sensitive, meaning main is different from Main .

The document.querySelector() method takes a  CSS selector  (or selectors) and returns the first element that matches the selector.

This method returns null if no element matches the specified selector.

Here's an example:

Check if an element exists in NodeList objects

Unlike the first two methods, the document.querySelectorAll() method returns a  NodeList  object.

This NodeList collection can contain zero or multiple elements that match the specified selectors. You can check the number of elements of a NodeList object via its length property. 

If the length is zero, it means no elements matches the selector.

The document.getElementByClassName() method also returns an array-like object called an HTMLCollection . The HTMLCollection interface has a length property too.

You can convert both NodeList and HTMLCollection objects into arrays with Array.from() methods:

Final notes

Always access DOM when the initial HTML document has been completely loaded and parsed. You might get unexpected results if you place your JavaScript code inside the <head> section.

The reason is the browser parses the document from top to bottom, and it might evaluate your JavaScript code before the elements are inserted into the DOM tree. 

Additionally, it's a good practice to place your JavaScript code before the closing body tag (just like the above example). 

If you have to place your code before the body tag, you can use the  DOMContentLoaded   event to ensure your code only runs after the DOM content is loaded:

If you get a ReferenceError when accessing the document, check this quick guide on fixing document is not defined error .

I hope these examples simplified the "javascript check if the element exists" problem for you.

Thanks for reading!

Author photo

Reza Lavarian Hey 👋 I'm a software engineer, an author, and an open-source contributor. I enjoy helping people (including myself) decode the complex side of technology. I share my findings on Twitter: @rezalavarian

❤️ You might be also interested in:

  • Cannot find module error in Node.js (Fixed)
  • How to fix "TypeError: map is not a function" in JavaScript
  • Add commas to numbers in JavaScript with these simple methods
  • SyntaxError: Unexpected end of JSON input in JavaScript (Fixed)
  • How to fix "ReferenceError: document is not defined" in JavaScript

Never miss a guide like this!

Disclaimer: This post may contain affiliate links . I might receive a commission if a purchase is made. However, it doesn’t change the cost you’ll pay.

  • Privacy Policy
  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

Optional chaining (?.)

The optional chaining ( ?. ) operator accesses an object's property or calls a function. If the object accessed or function called using this operator is undefined or null , the expression short circuits and evaluates to undefined instead of throwing an error.

Description

The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish ( null or undefined ), the expression short-circuits with a return value of undefined . When used with function calls, it returns undefined if the given function does not exist.

This results in shorter and simpler expressions when accessing chained properties when the possibility exists that a reference may be missing. It can also be helpful while exploring the content of an object when there's no known guarantee as to which properties are required.

For example, consider an object obj which has a nested structure. Without optional chaining, looking up a deeply-nested subproperty requires validating the references in between, such as:

The value of obj.first is confirmed to be non- null (and non- undefined ) before accessing the value of obj.first.second . This prevents the error that would occur if you accessed obj.first.second directly without testing obj.first .

This is an idiomatic pattern in JavaScript, but it gets verbose when the chain is long, and it's not safe. For example, if obj.first is a Falsy value that's not null or undefined , such as 0 , it would still short-circuit and make nestedProp become 0 , which may not be desirable.

With the optional chaining operator ( ?. ), however, you don't have to explicitly test and short-circuit based on the state of obj.first before trying to access obj.first.second :

By using the ?. operator instead of just . , JavaScript knows to implicitly check to be sure obj.first is not null or undefined before attempting to access obj.first.second . If obj.first is null or undefined , the expression automatically short-circuits, returning undefined .

This is equivalent to the following, except that the temporary variable is in fact not created:

Optional chaining cannot be used on a non-declared root object, but can be used with a root object with value undefined .

Optional chaining with function calls

You can use optional chaining when attempting to call a method which may not exist. This can be helpful, for example, when using an API in which a method might be unavailable, either due to the age of the implementation or because of a feature which isn't available on the user's device.

Using optional chaining with function calls causes the expression to automatically return undefined instead of throwing an exception if the method isn't found:

However, if there is a property with such a name which is not a function, using ?. will still raise a TypeError exception "someInterface.customMethod is not a function".

Note: If someInterface itself is null or undefined , a TypeError exception will still be raised ("someInterface is null"). If you expect that someInterface itself may be null or undefined , you have to use ?. at this position as well: someInterface?.customMethod?.() .

eval?.() is the shortest way to enter indirect eval mode.

Optional chaining with expressions

You can also use the optional chaining operator with bracket notation , which allows passing an expression as the property name:

This is particularly useful for arrays, since array indices must be accessed with square brackets.

Optional chaining not valid on the left-hand side of an assignment

It is invalid to try to assign to the result of an optional chaining expression:

Short-circuiting

When using optional chaining with expressions, if the left operand is null or undefined , the expression will not be evaluated. For instance:

Subsequent property accesses will not be evaluated either.

This is equivalent to:

However, this short-circuiting behavior only happens along one continuous "chain" of property accesses. If you group one part of the chain, then subsequent property accesses will still be evaluated.

Except the temp variable isn't created.

Basic example

This example looks for the value of the name property for the member bar in a map when there is no such member. The result is therefore undefined .

Dealing with optional callbacks or event handlers

If you use callbacks or fetch methods from an object with a destructuring assignment , you may have non-existent values that you cannot call as functions unless you have tested their existence. Using ?. , you can avoid this extra test:

Stacking the optional chaining operator

With nested structures, it is possible to use optional chaining multiple times:

Combining with the nullish coalescing operator

The nullish coalescing operator may be used after optional chaining in order to build a default value when none was found:

Specifications

Browser compatibility.

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • Nullish coalescing operator ( ?? )

IMAGES

  1. How to Check if a Property Exists in a JavaScript Object

    javascript assign if property exists

  2. 4 Ways to Check if the Property Exists in JavaScript Object

    javascript assign if property exists

  3. How to check if a property exists in an object in JavaScript

    javascript assign if property exists

  4. 4 Ways to Check if the Property Exists in JavaScript Object

    javascript assign if property exists

  5. 3 Ways to Check if Property exists in JS Object [2024]

    javascript assign if property exists

  6. How To Check If A Property Exists In A Javascript Object

    javascript assign if property exists

VIDEO

  1. Do You Know How Classes Actually Work (JavaScript Prototypes)

  2. Remove Properties From JavaScript Object (Copy) #javascript #javascriptlearning #javascriptdeveloper

  3. Property exists in JavaScript object #javascript #coding

  4. URL Shortener Microservice Solution FreeCodeCamp

  5. #6

  6. 16.3 JavaScript assign Value of one field to other in SAP Adobe forms

COMMENTS

  1. javascript

    Here the assumption is you want to make a key with the name value itself. Another approach. just do like this, const destination = {}; const value = getValue(); value && (destination.value = value); // here is the one liner way. This will make sure that the value attribute is getting create only if value is defined. edited Nov 15, 2022 at 10:27.

  2. javascript

    How to check if an object property exists, and conditionally assign default value (in JavaScript) 2. How to create a special OR statement in JavaScript. Hot Network Questions Why are the Lion Air and Ethiopian Airlines crashes being litigated in the US?

  3. How to check if a property exists in an object in JavaScript

    in Operator. The in operator is another way to check the presence of a property in an object in JavaScript. It returns true if the property exists in an object. Otherwise, it returns false. Let us use the in operator to look for the cake property in the food object: const food = {. pizza: '🍕',

  4. 3 Ways to Check If a Property Exists in an Object

    Use the hasOwnProperty() method to check if an property exists in the own properties of an object. Use the in operator to check if a property exists in both own properties and inherited properties of an object. Compare the property with undefined to check if a property exists only when you are sure that the initial value of the property is not ...

  5. How to Check if a Property Exists in a JavaScript 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 ...

  6. [5 Ways] Conditionally Add Property/Member to a JavaScript Object

    In JavaScript, Object.assign() is a built-in method that allows you to copy the values of all enumerable properties from one or more source objects to a target object. The syntax for Object.assign() is as follows: Syntax. Object.assign(target_obj, source_obj); We can also use the Object.assign method to add a member to an object conditionally

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

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

  8. Object.assign()

    Later sources' properties overwrite earlier ones. The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters. Therefore it assigns properties, versus copying or defining new properties.

  9. How to conditionally add a property to an object in JavaScript

    Implement Object.assign for dynamic properties Object.assign can also be used for conditional additions: Object . assign ( user , condition && { newProperty : 'newValue' } ) ;

  10. Object.defineProperty()

    When the property already exists, Object.defineProperty() attempts to modify the property according to the values in the descriptor and the property's current configuration. If the old descriptor had its configurable attribute set to false, the property is said to be non-configurable.It is not possible to change any attribute of a non-configurable accessor property, and it is not possible to ...

  11. How To Check if a Property Exists on a JavaScript Object

    2. The in Operator. The in operator returns true if a property exists on an object or along its prototype chain: The in operator does not suffer from the problem with falsy values. However, it also returns true for properties up the prototype chain. This might be what you want. If not, you should use the third method.

  12. Check if object has a specific property in JavaScript

    Lodash _.has() is a method that checks if an object has a direct property with a given path. It is similar to the native JavaScript Object.hasOwn() method, checks only for direct properties, ignoring inherited ones. It's convenient for checking nested properties using dot notation _.has(obj, 'x.y.z'), useful for validating input data and ...

  13. Object.hasOwn()

    The Object.hasOwn() method returns true if the specified property is a direct property of the object — even if the property value is null or undefined . The method returns false if the property is inherited, or has not been declared at all. Unlike the in operator, this method does not check for the specified property in the object's prototype ...

  14. Simpler Way To Conditionally Add Properties to Javascript Object

    Simpler Alternative. Instead of using the if statement, you can use the spread operator. The idea is simple: the spread operator merges the properties of the target object with the object it's being applied on and if the source object is null, it adds no properties. const x = { ...{ a: 2 } } // => x = { a : 2 } const y = { ...null } // => y = {}

  15. What's the correct way to test for existence of a property on a

    but this is only to know if such a property is defined in object itself, but not its parents. so if such property is inherited by the object, you can not test its existence like this. the other way is to test the property against undefined value. like this:

  16. JavaScript check if property exists in Object

    Using undefined to see if an object has a property. 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 ...

  17. How to check if an element exists in JavaScript (with examples)

    So to check if the element exists in the DOM, you need to check the returned value. The method document.getElementById() takes a case-sensitive string argument and returns the element whose id property matches the specified string. If the element doesn't exist, we'll get a null value.

  18. Optional chaining (?.)

    You can use optional chaining when attempting to call a method which may not exist. This can be helpful, for example, when using an API in which a method might be unavailable, either due to the age of the implementation or because of a feature which isn't available on the user's device. Using optional chaining with function calls causes the ...

  19. javascript

    This will add a property hello whose value is {world: 'Hello world!'} to the test object, if it doesn't exist. If you have a lot of these objects, you can just iterate over them and apply this function. Note: uses lodash.js. var test = {}; _.defaults(test, { hello: {world: 'Hello world!'}

  20. JavaScript

    Published Jan 4, 2024. Contribute to Docs. The .hasOwn() method verifies if a specific property exists in an object, returning true if present, otherwise false. Unlike the in operator, it solely inspects direct object properties and doesn't consider inherited ones. This method serves as a replacement for Object.hasOwnProperty().