{"id":4433,"date":"2022-10-04T08:20:44","date_gmt":"2022-10-04T13:20:44","guid":{"rendered":"https:\/\/www.becomebetterprogrammer.com\/?p=4433"},"modified":"2022-10-04T08:20:50","modified_gmt":"2022-10-04T13:20:50","slug":"cannot-convert-undefined-or-null-to-object-in-js","status":"publish","type":"post","link":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/cannot-convert-undefined-or-null-to-object-in-js\/","title":{"rendered":"(Solved) Cannot Convert Undefined or Null to Object in JS"},"content":{"rendered":"\n<p><strong>The error &#8220;TypeError: Cannot convert undefined or null to object&#8221; happens when JavaScript attempts to convert <code>null<\/code> and <code>undefined<\/code> to an object.<\/strong> Below you can see examples of when this error occurs. <\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/ \u274c Uncaught TypeError: Cannot convert undefined or null to object at Function.assign\nObject.assign(undefined, {});\nObject.assign(null, {});\n\n\/\/ \u274c TypeError: Cannot convert undefined or null to object at Function.keys\nObject.keys(undefined);\nObject.keys(null);\n\n\/\/ \u274c TypeError: Cannot convert undefined or null to object at Function.values\nObject.values(undefined);\nObject.values(null);<\/code><\/pre>\n\n\n\n<p>In the previous example, notice how the <code>Object.assign()<\/code> , <code>Object.keys()<\/code> , and <code>Object.values()<\/code> methods expect a parameter <code>o<\/code> equivalent to any JavaScript object <code>{}<\/code>. <\/p>\n\n\n\n<p class=\"has-vivid-green-cyan-background-color has-background\">? Interestingly, if you attempt passing a number, a string, or even a boolean when using the <code>Object.assign() <\/code>, <code>Object.keys()<\/code> , and <code>Object.values()<\/code> methods, JavaScript won&#8217;t generate an error.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/ \u2705 No errors generated\r\nObject.assign(1, {});\r\nObject.assign(true, {});\r\nObject.assign('Hello', {});\r\n\r\n\/\/ \u2705 No errors generated\r\nObject.keys(1);\r\nObject.keys(true);\r\nObject.keys('Hello');\r\n\r\n\/\/ \u2705 No errors generated\r\nObject.values(1);\r\nObject.values(true);\r\nObject.values('Hello');<\/code><\/pre>\n\n\n\n<p>What happens in this scenario is JavaScript attempts to identify if the values of the received parameters have the expected value type, such as a boolean,  a string, a number, an object, or an array (which is a special kind of object), etc.<\/p>\n\n\n\n<p class=\"has-pale-cyan-blue-background-color has-background\">? If the values of the received parameters are not an expected value type, for instance, an object, JavaScript will automatically attempt to transform the values to a given value type.<\/p>\n\n\n\n<p>That&#8217;s why the <code>Object.assign() <\/code>, <code>Object.keys() <\/code>, and <code>Object.values()<\/code> methods didn&#8217;t fail even after a value passed is different not an object. <\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_82_2 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\"><p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<\/div><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/cannot-convert-undefined-or-null-to-object-in-js\/#How_to_solve_or_prevent_getting_the_error_%E2%80%9CTypeError_Cannot_convert_undefined_or_null_to_object%E2%80%9D\" >How to solve or prevent getting the error &#8220;TypeError: Cannot convert undefined or null to object&#8221;<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/cannot-convert-undefined-or-null-to-object-in-js\/#Use_conditional_checks_prior_to_triggering_methods_expecting_an_object\" >Use conditional checks prior to triggering methods expecting an object<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/cannot-convert-undefined-or-null-to-object-in-js\/#Use_the_nullish_coalescing_operator_to_use_a_fallback_value\" >Use the nullish coalescing operator (??) to use a fallback value<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/cannot-convert-undefined-or-null-to-object-in-js\/#Use_the_logical_OR_operator_to_use_a_fallback_value\" >Use the logical OR (||) operator to use a fallback value<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/cannot-convert-undefined-or-null-to-object-in-js\/#Use_TryCatch_statements_to_detect_errors\" >Use Try\/Catch statements to detect errors<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/cannot-convert-undefined-or-null-to-object-in-js\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"How_to_solve_or_prevent_getting_the_error_%E2%80%9CTypeError_Cannot_convert_undefined_or_null_to_object%E2%80%9D\"><\/span>How to solve or prevent getting the error &#8220;TypeError: Cannot convert undefined or null to object&#8221;<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Fortunately,<strong> here there are different alternatives to solve or prevent getting the error &#8220;TypeError: Cannot convert undefined or null to object&#8221;<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Use conditional checks prior to triggering methods expecting an object.<\/strong><\/li><li><strong>Use the nullish coalescing operator (<code>??<\/code>) to use a fallback value.<\/strong><\/li><li><strong>Use the logical OR (<code>||<\/code>) operator to use a fallback value.<\/strong><\/li><li><strong>Use  <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Statements\/try...catch\" target=\"_blank\" rel=\"noopener\">Try\/Catch<\/a> statements to detect errors.<\/strong><\/li><\/ul>\n\n\n\n<p>Let&#8217;s see the examples of the solutions mentioned above. However, instead of showing the examples by explicitly passing <code>undefined<\/code>s and  <code>null<\/code> s, you will see a more realistic scenario. <\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const CARS = &#91;\n  {\n    year: 2012,\n    brand: \"Dodge\",\n    model: \"Challenger\",\n    color: \"Black\"\n  }\n];\n\n\/\/ the value of the 'toyota variable will be undefined\nconst toyota = CARS.find(car => {\n  return car.brand === \"Toyota\";\n});\n\n\/\/ \u274c TypeError: Cannot convert undefined or null to object at Function.values\nconst toyotaValues = Object.values(toyota); <\/code><\/pre>\n\n\n\n<p>In the previous snippet of code, the <code>toyota<\/code> variable is undefined because the <code>CARS<\/code> array doesn&#8217;t contain an element with a Toyota brand after running the predicate passed to the <code>array.find()<\/code> method on all the elements of the array. In fact, <a href=\"https:\/\/www.becomebetterprogrammer.com\/typescript-array-find-possibly-undefined\/\">there&#8217;s always the possibility of expecting an undefined value from running the <code>array.find()<\/code><\/a>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Use_conditional_checks_prior_to_triggering_methods_expecting_an_object\"><\/span>Use conditional checks prior to triggering methods expecting an object<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>To fix the error <code>TypeError: Cannot convert undefined or null to object at Function.values<\/code> caused in the example above, use conditional checks prior to triggering the <code>Object.values<\/code> method to ensure the <code>toyota<\/code> variable is an object. Here are examples of different checks you could do.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>let toyotaValues = &#91;];\n\n\/\/ ? Use the double exclamation marks or \"double bangs\" to cast a true Boolean value\n\/\/ in case toyota variable is an object\nif (!!toyota) {\n   toyotaValues.push(...(Object.values(toyota));\n}\n\n\/\/ ? Use the keyword typeof to detect the type of the value of toyota \nif (typeof toyota !== 'undefined') {\n   toyotaValues.push(...(Object.values(toyota));\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Use_the_nullish_coalescing_operator_to_use_a_fallback_value\"><\/span>Use the nullish coalescing operator (<code>??<\/code>) to use a fallback value<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Another solution is to use the <a href=\"https:\/\/www.becomebetterprogrammer.com\/typescript-double-question-marks\/\">nullish coalescing operator (<code>??<\/code><\/a>) to use a fallback value object in case the original value is <code>undefined<\/code> or <code>null<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/ \u2705 Using the nullish coalescing operator is a clean way to prevent errors\n\/\/ ocurred from using undefined or null values\nconst toyotaValues = Object.values(toyota ?? {\n    year: 2018,\n    brand: \"Toyota\",\n    model: \"Prius\",\n    color: \"Black\"\n  };<\/code><\/pre>\n\n\n\n<p>In this way, if the <code>toyota<\/code> variable is <code>undefined<\/code> or <code>null<\/code>, the <code>Object.values()<\/code> method will use the fallback object value.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>{\n    year: 2018,\n    brand: \"Toyota\",\n    model: \"Prius\",\n    color: \"Black\"\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Use_the_logical_OR_operator_to_use_a_fallback_value\"><\/span>Use the logical OR (<code>||<\/code>) operator to use a fallback value<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Similar to the previous solution, you can use the <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Operators\/Logical_OR\" target=\"_blank\" rel=\"noopener\">logical OR<\/a> (<code>||<\/code>) operator to use a fallback value object in case the original value is <code>undefined<\/code> or <code>null<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/ \u2705 Using the logical OR (||) is a clean way to prevent errors\n\/\/ ocurred from using undefined or null values\nconst toyotaValues = Object.values(toyota ?? {\n    year: 2018,\n    brand: \"Toyota\",\n    model: \"Prius\",\n    color: \"Black\"\n  };<\/code><\/pre>\n\n\n\n<p><a href=\"https:\/\/www.becomebetterprogrammer.com\/typescript-double-question-marks\/\">While the nullish coalescing operator and the logical OR operator seem to work in the same way, they don&#8217;t behave the same.<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Use_TryCatch_statements_to_detect_errors\"><\/span>Use Try\/Catch statements to detect errors<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Finally but not least, you can wrap the logic of the code between a <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Statements\/try...catch\" target=\"_blank\" rel=\"noopener\">try and catch<\/a> to prevent the code from crashing at runtime.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>try {\n  const CARS = &#91;\n    {\n      year: 2012,\n      brand: \"Dodge\",\n      model: \"Challenger\",\n      color: \"Black\"\n    }\n  ];\n  \n  \/\/ the value of the 'toyota variable will be undefined\n  const toyota = CARS.find(car => {\n    return car.brand === \"Toyota\";\n  });\n  \n  \/\/ \u274c Expected Error: TypeError: Cannot convert undefined or null to object at Function.values\n  const toyotaValues = Object.values(toyota);\n  \n   \/\/ \u2705 The program doesn't crash at runtime even as the error is wrapped inside a try\/catch\n} catch (error) {\n  console.error('Oh no! There was an error ', error);\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>All in all, the error &#8220;TypeError: Cannot convert undefined or null to object&#8221; happens when attempting to convert a <code>null<\/code> and <code>undefined<\/code> values to an object. To prevent this error from happening<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Use conditional checks prior to triggering methods expecting an object.<\/li><li>Use the nullish coalescing operator (??) to use a fallback value.<\/li><li>Use the logical OR (||) operator to use a fallback value.<\/li><li>Use Try\/Catch statements to detect errors.<\/li><\/ul>\n","protected":false},"excerpt":{"rendered":"<p>The error &#8220;TypeError: Cannot convert undefined or null to object&#8221; happens when JavaScript attempts to convert null and undefined to an object. Below you can see examples of when this error occurs. In the previous example, notice how the Object.assign() , Object.keys() , and Object.values() methods expect a parameter o equivalent to any JavaScript object &#8230; <a title=\"(Solved) Cannot Convert Undefined or Null to Object in JS\" class=\"read-more\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/cannot-convert-undefined-or-null-to-object-in-js\/\" aria-label=\"More on (Solved) Cannot Convert Undefined or Null to Object in JS\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":4436,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"nf_dc_page":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[16],"tags":[],"class_list":["post-4433","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-javascript","generate-columns","tablet-grid-50","mobile-grid-100","grid-parent","grid-50"],"_links":{"self":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/4433","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/comments?post=4433"}],"version-history":[{"count":3,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/4433\/revisions"}],"predecessor-version":[{"id":4438,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/4433\/revisions\/4438"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media\/4436"}],"wp:attachment":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media?parent=4433"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/categories?post=4433"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/tags?post=4433"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}