{"id":175,"date":"2023-11-06T14:40:47","date_gmt":"2023-11-06T14:40:47","guid":{"rendered":"https:\/\/favtutor.com\/articles\/?p=175"},"modified":"2023-11-08T09:27:37","modified_gmt":"2023-11-08T09:27:37","slug":"check-if-key-exists-in-javascript-object","status":"publish","type":"post","link":"https:\/\/favtutor.com\/articles\/check-if-key-exists-in-javascript-object\/","title":{"rendered":"How to Check if a Key Exists in JavaScript Objects?"},"content":{"rendered":"\n<p>Javascript is the language of the web. It is a scripting language, i.e. it is not compiled but rather interpreted line by line. In this article, we will be taking a deep dive into what Javascript objects and keys are, and how to check if a key exists in an object. We will discuss various methods to check for key existence in an object.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>What are Objects in JavaScript?<\/strong><\/h2>\n\n\n\n<p>Just like we use hashmaps in C++ that store data in the form of \u201ckey-value\u201d pairs, We use Javascript object to store data in the same way, i.e. in the form of key-value pairs. So, all in all, <strong>Objects are non-primitive data types in Javascript that store an unordered collection of key-value pairs. <\/strong>The association between key-value is called property, so objects are a collection of properties.<\/p>\n\n\n\n<p>For example, we have defined an object \u201ccar\u201d with various properties below.<\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>let car = {\n&nbsp;&nbsp;&nbsp;&nbsp;name: \"WagonR\",\n&nbsp;&nbsp;&nbsp;&nbsp;model: 2015,\n&nbsp;&nbsp;&nbsp;&nbsp;price: 340000\n};<\/code><\/pre>\n\n\n\n<p>Several properties such as name, model, and price are defined for the object \u201ccar\u201d. The name, model, and price here indicate the keys, and \u201cWagonR\u201d, 2015 and 340000 are the values corresponding to the related keys.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>What are the Keys in JavaScript?<\/strong><\/h2>\n\n\n\n<p>As discussed in the previous section, <strong>keys are typically used as the names or the identifiers to access the object\u2019s properties.<\/strong>&nbsp;<\/p>\n\n\n\n<p>Let\u2019s take an example. Say we have an object \u201cstudent\u201d and the student has several properties like firstName, lastName, rollnumber, and age.&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>let student = {\n&nbsp;&nbsp;&nbsp;&nbsp;firstName:\"Joshua\",\n&nbsp;&nbsp;&nbsp;&nbsp;lastName:\"Benz\",\n&nbsp;&nbsp;&nbsp;&nbsp;rollnumber:2000104,\n&nbsp;&nbsp;&nbsp;&nbsp;age:16\n};<\/code><\/pre>\n\n\n\n<p>The keys here are <em>firstName, lastName, rollnumber, and age<\/em> as they are used to specify the names of the properties which in turn have corresponding values.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>How to Check if the Key Exists in an Object?<\/strong><\/h2>\n\n\n\n<p>Now, we know about objects and keys. What if we want to check if a key exists in an object? Taking the previous example only, if we want to check whether the key \u2018age\u2019 is present in the object \u2018student\u2019 or not, how do we do this? Let\u2019s take a look.<\/p>\n\n\n\n<p>There are several techniques to check if a key exists in an object.&nbsp;<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Using the \u2018in\u2019 Operator<\/strong><\/h3>\n\n\n\n<p><strong>The best method to check for existing keys is with the use of the \u2018in\u2019 operator.<\/strong> It is a simple and easy method to check if an object contains the key. The operator returns a boolean value indicating if a specified key is present in an object. If it returns true, it means that the key exists in the object. If it returns false, it means that the object doesn\u2019t contain that particular key.<\/p>\n\n\n\n<p><strong>Syntax:<\/strong><\/p>\n\n\n\n<p>The syntax for using the \u201cin\u201d operator is:&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>\u2018key\u2019 in object_name;<\/code><\/pre>\n\n\n\n<p>Let us understand it with the help of an example. We have an object \u2018employee\u2019 with certain properties(key-value pairs). We will check if the object employee contains a certain key or not. The code to check using the \u201cin\u201d operator is given below.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/ecmascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/defining an object employee\nlet employee={\n\u00a0\u00a0\u00a0\u00a0empId:2301,\n\u00a0\u00a0\u00a0\u00a0name: &quot;Joshua&quot;,\n\u00a0\u00a0\u00a0\u00a0email:&quot;josh232@gmail.com&quot;,\n\u00a0\u00a0\u00a0\u00a0age:32\n};\n\n\/\/both the statements below return true\n'name' in employee;\n'age' in employee;\n\n\/\/below statement returns false\n'salary' in employee<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>true\ntrue\nfalse<\/code><\/pre>\n\n\n\n<p>The above code checks if the name and age keys exist in the object \u2018employee\u2019 and hence returns true, whereas returns false when checking for the key \u2018salary\u2019 as it doesn\u2019t exist in the object.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Using the Inbuilt \u2018hasOwnProperty() Method<\/strong><\/h3>\n\n\n\n<p>The second method to check if an object contains a key is by using an inbuilt \u2018hasOwnProperty()\u2019 method. <strong>The hasOwnProperty() method takes an argument in the string form as the parameter and checks whether that string (the key) is present in the object or not.<\/strong> It returns a <strong>boolean<\/strong> value. If it returns true, it means that the key exists in the object. If it returns false, it means that the object doesn\u2019t contain that particular key<\/p>\n\n\n\n<p><strong>Syntax:<\/strong><\/p>\n\n\n\n<p>The<strong> <\/strong>syntax for using this method is as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>object_name.hasOwnProperty(\u2018key_name\u2019)<\/code><\/pre>\n\n\n\n<p>Let us understand it with the help of the previous example. We have an object \u2018employee\u2019 with certain properties(key-value pairs). Now, We will check if the object employee contains a certain key or not using this method. The code for the same is given below.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/defining an object employee\nlet employee={\n    empId:2301,\n    name: &quot;Joshua&quot;,\n    email:&quot;josh232@gmail.com&quot;,\n    age:32\n};\n\n\/\/both the statements below return true\nconsole.log(employee.hasOwnProperty('name'));\nconsole.log(employee.hasOwnProperty('age'));\n\n\/\/below statement returns false\nconsole.log(employee.hasOwnProperty('salary'));<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>true\ntrue\nfalse<\/code><\/pre>\n\n\n\n<p>The code above uses the inbuilt method \u2018hasOwnProperty(\u2018key_name\u2019)\u2019 and returns true for the keys &#8211; name and age. It returns false when checking for \u201csalary\u201d as the key.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Optional Chaining<\/strong><\/h3>\n\n\n\n<p>Besides the previous techniques, there is also one other method to check if a key exists in an object. But, it\u2019s a relatively new feature introduced in ECMAScript 2020, and may not be supported in all JavaScript environments.&nbsp;<\/p>\n\n\n\n<p><strong>The Optional Chaining method allows you to check if a key exists and access its value in a single line.<\/strong> If a key exists, it returns the value corresponding to the key and If the key does not exist, it returns undefined. The optional chaining operator is &#8216;?.&#8217; to check if the key exists before accessing its value.<\/p>\n\n\n\n<p>Let\u2019s understand with the help of an example below.&nbsp;<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/defining an object employee\nlet employee={\n    empId:2301,\n    name: &quot;Joshua&quot;,\n    email:&quot;josh232@gmail.com&quot;,\n    age:32\n};\n\n\/\/below statement returns Joshua as the name\nconsole.log(employee?.name);\n\n\/\/below statement returns 32 as the age\nconsole.log(employee?.age);\n\n\/\/below statement returns undefined\nconsole.log(employee?.salary);<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>Joshua\n32\nundefined<\/code><\/pre>\n\n\n\n<p>In the code above, the optional chaining operator <em>returns the values corresponding to the keys<\/em> for the keys which are present in the object(such as name and age). It returns undefined for the keys (such as salary) which are not present in the object.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Understanding the Limitations<\/strong><\/h2>\n\n\n\n<p>Let\u2019s discuss the limitations of the above mentioned methods that help us check if a key exists in an object or not.<\/p>\n\n\n\n<p>Let\u2019s use the previous example but explicitly set the property \u2018email\u2019 to &#8216;undefined&#8217; but not delete it from the object.The behavior of the \u2018in\u2019 operator and \u2018hasOwnProperty()\u2019 method will be different than that of the \u2018Optional Chaining\u2019 method.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/defining an object employee with email of the employee as 'undefined'\nlet employee={\n    empId:2301,\n    name: &quot;Joshua&quot;,\n    email:undefined,\n    age:32\n};\n\n\/\/below statement uses the 'in' operator to check if the key exist\nconsole.log('email' in employee);\n\n\/\/below statement uses the hasOwnProperty() to check if object contains the key\nconsole.log(employee.hasOwnProperty('email'));\n\n\/\/below statement uses the optional chaining method to check if the email exists\nconsole.log(employee?.email);<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>true\ntrue\nundefined<\/code><\/pre>\n\n\n\n<p>It\u2019s clear from the output that even if \u2018email\u2019 property is set to \u2018undefined\u2019, the \u2018in\u2019 operator method and the \u2018hasOwnProperty()\u2019 still return \u201ctrue\u201d, i.e. the key exists. Whereas, the optional chaining method returns undefined.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Custom Methods to check Key Existence<\/strong><\/h2>\n\n\n\n<p>In certain scenarios, the standard methods may not be sufficient to check for key existence. Let\u2019s take an example.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">let employee = {\n    empId:2301,\n    name: &quot;Joshua&quot;,\n    email:&quot;josh232@gmail.com&quot;,\n    age:32,\n    address:{\n        city:&quot;Tokyo&quot;,\n        country:&quot;Japan&quot;\n    }\n};\n\/\/below statement returns false\nconsole.log('city' in employee);\n\n\/\/below statement returns true\nconsole.log('city' in employee.address);<\/pre><\/div>\n\n\n\n<p>In the code given above, if we check whether the key \u2018city\u2019 exists in the employee or not using the \u2018in\u2019 operator or any other standard method, it will give the output as false.&nbsp;<\/p>\n\n\n\n<p>But, when we check it to be present in the address property of the employee, it returns true which is somehow contradicting because <strong>address is a property of employee and city is a property of address, so indirectly city becomes a property for the employee object as well<\/strong>.<\/p>\n\n\n\n<p>To get the correct output, we need to make a custom function which checks the key existence in nested objects as well. Here&#8217;s an example of how you can use Object.keys() and some() to check if a key exists in an object and its nested objects:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">let employee = {\n    empId:2301,\n    name: &quot;Joshua&quot;,\n    email:&quot;josh232@gmail.com&quot;,\n    age:32,\n    address:{\n        city:&quot;Tokyo&quot;,\n        country:&quot;Japan&quot;\n    }\n};\n\n\/\/custom function to check if key exists in an object\nconst checkIfKeyExists = (object, key) =&gt; {\n  let keys = Object.keys(object);\n  return keys.some(k =&gt; k === key || (typeof object[k] === &quot;object&quot; &amp;&amp; checkIfKeyExists(object[k], key)));\n};\n \n\/\/now below statement will return true\nconsole.log(checkIfKeyExists(employee, &quot;city&quot;));<\/pre><\/div>\n\n\n\n<p>In the code above, the checkIfKeyExists() function recursively checks if a key exists in an object and its nested objects. It uses the Object.keys() method to retrieve all the keys of an object and the some() method to iterate over the keys and check if the specified key exists.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Important Points to Keep in Mind&nbsp;<\/strong><\/h2>\n\n\n\n<p>While checking if a key exists in an object, it becomes important to keep in mind some best practices to ensure efficient and reliable code.&nbsp;<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use the appropriate method based on your requirements. \u2018In\u2019 operator and \u2018hasOwnProperty()\u2019 methods are the standard approaches.<br><\/li>\n\n\n\n<li>Consider the limitations of both the methods. <strong>Note that both the in operator and hasOwnProperty() method may return true for properties explicitly set to &#8216;undefined&#8217; or not deleted from the object.<\/strong><br><\/li>\n\n\n\n<li>It is necessary to handle edge cases and uncommon conditions as necessary. Depending on your specific use case, you may need to explore alternative methods or custom functions to handle nested objects or specific conditions.<br><\/li>\n\n\n\n<li>It is important to test your code thoroughly. Ensure that you test your key existence checks with various scenarios.<br><\/li>\n\n\n\n<li>Stay up to date with the latest JavaScript features. Keep an eye on new features like optional chaining that can simplify key existence checks and improve code readability.<\/li>\n<\/ul>\n\n\n\n<p>By following these best practices, you can write more reliable and efficient code when checking for key existence in JavaScript objects.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>In this article, we discussed JavaScript objects and keys. Then, we dwelled further into various methods to check if an object contains a key. The &#8216;in&#8217; operator and \u2018hasOwnProperty()\u2019 method are the standard approaches. Additionally, we discussed the optional chaining method that is used to handle the undefined values. By understanding the available methods and their limitations, one can effectively check for key existence in JavaScript objects and build more robust applications.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Javascript is the language of the web. It is a scripting language, i.e. it is not compiled but rather interpreted line by line. In this article, we will be taking a deep dive into what Javascript objects and keys are, and how to check if a key exists in an object. We will discuss various [&hellip;]<\/p>\n","protected":false},"author":9,"featured_media":191,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jnews-multi-image_gallery":[],"jnews_single_post":null,"jnews_primary_category":{"id":"","hide":""},"footnotes":""},"categories":[9],"tags":[11,10],"class_list":["post-175","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-web-development","tag-javascript","tag-javascript-object"],"_links":{"self":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/175","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/users\/9"}],"replies":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/comments?post=175"}],"version-history":[{"count":15,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/175\/revisions"}],"predecessor-version":[{"id":278,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/175\/revisions\/278"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media\/191"}],"wp:attachment":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media?parent=175"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/categories?post=175"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/tags?post=175"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}