{"id":2904,"date":"2022-07-10T11:55:01","date_gmt":"2022-07-10T16:55:01","guid":{"rendered":"https:\/\/www.becomebetterprogrammer.com\/?p=2904"},"modified":"2022-07-10T11:55:05","modified_gmt":"2022-07-10T16:55:05","slug":"javascript-how-the-question-mark-works","status":"publish","type":"post","link":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-how-the-question-mark-works\/","title":{"rendered":"JavaScript | How does the Question Mark(?) Work? (examples)"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Have you seen a question mark (?) in JavaScript code but you don&#8217;t know what it means? What if I tell you the question mark can have not only one meaning, but three different meanings in JavaScript based on how it is used? All of the sudden, the question mark can sound complicated. However, once you know what it is, you will start using it often on your codebase. After, what does the question mark mean?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Depending on the context being used, the question mark (?) in JavaScript can work in three different ways:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li><strong>As a Ternary Operator<\/strong><\/li><li><strong>As a Null Coalescing Operator<\/strong><\/li><li><strong>As Optional Chaining Operator<\/strong><\/li><\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">This article will explain and demonstrate how the question mark (?) operator works as a ternary operator, as a null coalescing operator, and as an optional chaining operator. <\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_83 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\/javascript-how-the-question-mark-works\/#How_does_the_question_mark_work_as_a_Ternary_Operator\" >How does the question mark (?) work as a Ternary Operator?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-how-the-question-mark-works\/#How_does_the_question_mark_work_as_a_Nullish_Coalescing_Operator\" >How does the question mark (?) work as a Nullish Coalescing Operator?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-how-the-question-mark-works\/#How_does_the_question_mark_work_as_a_Optional_Chaining_Operator\" >How does the question mark (?) work as a Optional Chaining Operator?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-how-the-question-mark-works\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"How_does_the_question_mark_work_as_a_Ternary_Operator\"><\/span><a id=\"post-2904-_25xsj63ee4e4\"><\/a>How does the question mark (?) work as a Ternary Operator?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>The question mark (?) used in the ternary operator separates the expression to be evaluated and the statement to be executed if the expression is true. And the colon operator (:) separates the statements in the truth block and the statements in the false block.<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The term \u201cternary\u201d means associated with three elements. Now, you might get your answer why the operator is called ternary. Yes, it is because the operator takes three operands: the condition, the truth block, and the false block. Let&#8217;s look at the syntax below to get a clear view of it.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>condition ? statement1 : statement2<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">If the <strong><code>condition<\/code><\/strong> is true, then <code><strong>statment1<\/strong><\/code> will get executed, and if the <strong><code>condition<\/code><\/strong> is false, then <code><strong>statement2<\/strong><\/code> will get executed. Let\u2019s implement a conditional check with the ternary operator.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const age = 20; \nage >= 18 ? console.log(\"You are eligible to vote\") : console.log(\"You are not eligible to vote\") \n\n\/\/prints \"You are eligible to vote<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s consider 18 as the minimum legal age to vote. The above program shows the voting eligibility for the age of 20. In contrast to the <strong>if<\/strong>&#8211;<strong>else<\/strong> statement, the job gets done in one line and is more readable. Now, it makes sense how the ternary operator is a short-hand alternative to the <strong>if<\/strong>&#8211;<strong>else<\/strong> statement.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In JavaScript, apart from false, some other expressions also represent the <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Glossary\/Falsy\" target=\"_blank\" rel=\"noopener\">falsy<\/a> values. These are<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>null<\/li><li>NaN<\/li><li>0<\/li><li>the empty string (&#8220;&#8221;)<\/li><li>undefined<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">If these expressions are evaluated in the ternary operator, the false block will get executed. Let\u2019s see an example below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>let person = \"\" \nname = person ? person : `user` \nconsole.log(`hey ${name}`) \/\/ \"hey user\"<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In the example above, since the <strong><code>person<\/code><\/strong> variable is empty, the variable is evaluated as false, and the false block is executed.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"How_does_the_question_mark_work_as_a_Nullish_Coalescing_Operator\"><\/span><a id=\"post-2904-_yvz0rdvkcyvl\"><\/a>How does the question mark (?) work as a Nullish Coalescing Operator?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Another scenario where the question mark (?) is used in JavaScript is in the null coalescing operator. <strong>The two question mark symbol (??) forms the null coalescing operator. The operator takes two operands on either side. The expression returns the right-hand side operand if the left-hand side operator is <code>null<\/code> or <code>undefined<\/code>. If it is not the case, the expression returns the left-hand side operator. <\/strong>The syntax of the operator is shown below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>statement1 ?? statement2<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here, <code><strong>statement2<\/strong><\/code> will be evaluated only if <code><strong>statement1<\/strong><\/code> is <strong><code>null<\/code><\/strong> or <code><strong>undefined<\/strong><\/code>; else, <code><strong>statement1<\/strong><\/code> will be evaluated. The need for the null coalescing operator rises when a default value is needed in case the required value is unavailable. For example, let\u2019s consider an application where the user needs to upload their profile picture. If the user has not uploaded their picture, the null coalescing operator can be used to upload a dummy picture. Let\u2019s see the example of the null coalescing operator.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>let person = null \nconst name = person ?? 'user' \nconsole.log(`hey ${name}`) \/\/ \"hey user\"<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here, the <strong><code>person<\/code><\/strong> variable has a <code><strong>null<\/strong><\/code> value. As a result, the name variable in the second line holds the value &#8220;user&#8221;, which is its right-hand side operand. If the <strong><code>person<\/code><\/strong> variable had any other value instead of <code><strong>null<\/strong><\/code> or <code><strong>undefined<\/strong><\/code>, it would evaluate that value. The example is shown below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>let person = \"Harry\" \nconst name = person ?? 'user' \nconsole.log(`hey ${name}`) \/\/ \"hey Harry\"<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Now, you might wonder how the null coalescing operator works if the left-hand side operand has a <code><strong>false<\/strong><\/code> or an empty value. Yes, this is a contrasting behavior of this operator compared to the ternary operator. The null coalescing operator will return the left-hand side operand even though they are falsy or have an empty value. It is because these values are neither <code><strong>null<\/strong><\/code> nor <code><strong>undefined<\/strong><\/code>. Let\u2019s see the example below to understand this behavior.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>let person1 = \"\" \nconst name1 = person1 ?? 'user' \nconsole.log(`hey ${name1}`) \/\/ \"hey \" \n\nlet person2 = false \nconst name2 = person2 ?? 'user' \nconsole.log(`hey ${name2}`) \/\/ \"hey false\"<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"How_does_the_question_mark_work_as_a_Optional_Chaining_Operator\"><\/span>How does the question mark (?) work as a Optional Chaining Operator?<a id=\"post-2904-_rr7ib5hcx2kz\"><\/a><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>The optional chaining operator (?.) provides a way to check the values of nested objects in a chain of objects without explicitly checking whether each object is null or undefined. <\/strong>If any reference in the chain is null or undefined, instead of an error message, <strong><code>undefined<\/code> <\/strong>is returned. There is no need to check whether each reference is <code><strong>null<\/strong><\/code> and <code><strong>undefined<\/strong><\/code> in the chain of objects. Thus, it provides a short and concise way to access the deep-nested object in a chain of objects.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">As you have already known the ternary operator, let&#8217;s understand the working mechanism of the optional chaining operator represented using the ternary operator.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>let user = {} \nlet name = (user !== null || user !== undefined) ? user.name: undefined; \nconsole.log(name)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The translation of the above code snippet using optional chaining is shown below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>let user = {} \nlet name = user?.name \nconsole.log(name)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Since the <strong><code>user<\/code><\/strong> object is <code><strong>null<\/strong><\/code>, the optional chaining returns undefined.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">An error message will be shown when you use the <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Operators\/Property_accessors#dot_notation\" target=\"_blank\" rel=\"noopener\">chaining operator (.)<\/a> to access the property that does not exist within an object.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>let country = {} \r\nconsole.log(country.state.city) \/\/ TypeError: country.state is undefined<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In such a situation, you can use the optional chaining as follows.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>let country = {} \nconsole.log(country?.state?.city) \/\/ undefined<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Instead of showing an error, it returns <code><strong>undefined<\/strong><\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If it weren&#8217;t for the optional chaining, you would not be able to write such elegant expressions. Let\u2019s consider an example where you use the <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Operators\/Logical_AND\" target=\"_blank\" rel=\"noopener\">logical AND operator (&amp;&amp;)<\/a>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>let country = {} \nconsole.log(country &amp;&amp; country.state &amp;&amp; country.state.city) \/\/ undefined<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In the example above, there is the repetitive use of the <strong><code>country<\/code><\/strong> and <code><strong>country.state<\/strong><\/code> objects. The use of optional chaining eliminates the problem.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span><a id=\"post-2904-_s7eraa41qz9e\"><\/a>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><a id=\"post-2904-_i7kjh9ytqwz3\"><\/a>The question mark (?) is used in various operators in JavaScript like the ternary operator, null coalescing operator, and the optional chaining operator. In this article, you learned how the question mark (?) fits in these operators. You also came to know how these operators work and simplify the tasks while evaluating different expressions in JavaScript.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Did this article help you understand how the question mark (?) works in JavaScript?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Let us know by replying on <a href=\"https:\/\/twitter.com\/bbprogrammer\" target=\"_blank\" rel=\"noopener\">Twitter of Become A Better Programmer<\/a> or to my <a href=\"https:\/\/twitter.com\/arealesramirez\" target=\"_blank\" rel=\"noopener\">personal Twitter account<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Have you seen a question mark (?) in JavaScript code but you don&#8217;t know what it means? What if I tell you the question mark can have not only one meaning, but three different meanings in JavaScript based on how it is used? All of the sudden, the question mark can sound complicated. However, once &#8230; <a title=\"JavaScript | How does the Question Mark(?) Work? (examples)\" class=\"read-more\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-how-the-question-mark-works\/\" aria-label=\"More on JavaScript | How does the Question Mark(?) Work? (examples)\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":2906,"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-2904","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\/2904","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=2904"}],"version-history":[{"count":1,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/2904\/revisions"}],"predecessor-version":[{"id":2905,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/2904\/revisions\/2905"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media\/2906"}],"wp:attachment":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media?parent=2904"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/categories?post=2904"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/tags?post=2904"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}