Nullish coalescing operator (??)
Tags: webdev, javascript, beginners, tutorial
Published: 2020-07-13 16:37:22

<!-- wp:paragraph -->
<p>The <strong>nullish coalescing operator (??)</strong> is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Example:</p>
<!-- /wp:paragraph -->

```javascript
const username = null ?? 'suprabha';
console.log(username);
// suprabha
```

<!-- wp:paragraph -->
<p></p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Contents:</h3>
<!-- /wp:heading -->

<!-- wp:quote -->
<blockquote class="wp-block-quote"><p>1.    Nullish coalescing operator (??)</p><p>2.    "&amp;&amp;" or "||" </p><p>3.    Falsy Value</p><p>4.     No chaining with "&amp;&amp;" or "||" operators</p><p>5.     Browser Support</p><p>6.     Reference</p></blockquote>
<!-- /wp:quote -->

<!-- wp:paragraph -->
<p>As you know "<strong>&amp;&amp;</strong>" or "<strong>||</strong>" operators are used to handle ‘truthy’ and ‘falsy’ values.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>Falsy value in JavaScript:</strong></p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>null</li><li>undefined</li><li>0</li><li>NaN</li><li>false</li><li>" "</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>"&amp;&amp;" or "||" operators work well with null or undefined values, but many false values can produce unexpected results.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let's take an example, here we want to process the response where value is 0(zero). So when you get the response which is falsy, so it will return the right-hand side value.</p>
<!-- /wp:paragraph -->

```javascript
const response = {
     count : 0
}
const count = response.count || 1;
console.log(count) // 1
```

<!-- wp:paragraph -->
<p>To make it work, we will use nullish coalescing operator “??”.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The nullish coalescing operator “??” acts very similar to the operator “||,” except that it doesn’t use “truthy” when evaluating the operator. Instead, it uses the definition of “nullish,” which means that the value is strictly equal to null or undefined.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We will take the same example:</p>
<!-- /wp:paragraph -->

```javascript
const response = {
     count : 0
}
const count = response.count ?? 1;
console.log(count) // 0
```

<!-- wp:heading {"level":3} -->
<h3>Few Important Points:</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p><strong>1. </strong> With operator “||” if the first operand is truthy, it evaluates to the first    operand. Otherwise, it evaluates to the second. With Nullish Coalescing operator, if the first operator is falsy but not nullish, it evaluates to the second operand.  </p>
<!-- /wp:paragraph -->

```javascript
console.log(false || true);//true
console.log(false ?? true);//false
```

<!-- wp:paragraph -->
<p><strong>2</strong>.  Zero is evaluated as a falsy value; hence the expression evaluates to the right-hand value using the “|| operator.” But, with Nullish Coalescing operator, zero is not null. Therefore, the expression evaluates to the left-hand value.</p>
<!-- /wp:paragraph -->

```javascript
console.log(0 || 1); //1
console.log(0 ?? 1); //0
```

<!-- wp:paragraph -->
<p><strong>3.  </strong>Empty string "" is evaluated as a falsy value; hence the expression evaluates to the right-hand value using the “|| operator.” But, with Nullish Coalescing operator, empty string "" is not null. Therefore, the expression evaluates to the left-hand value.</p>
<!-- /wp:paragraph -->

```javascript
console.log('' || 'supi!');//supi      
console.log('' ?? 'supi');//''
```

<!-- wp:paragraph -->
<p><strong>4.  </strong>If you check with the undefined or null it will be same:</p>
<!-- /wp:paragraph -->

```javascript
console.log(undefined || 10); // 10
console.log(undefined ?? 10); // 10
console.log(null || 100); // 100
console.log(null ?? 100); // 100
```

<!-- wp:paragraph -->
<p>Going to cover more example for better understanding:</p>
<!-- /wp:paragraph -->

```javascript
const response = {
  settings: {
    nullValue: null,
    height: 400,
    animationDuration: 0,
    headerText: '',
    showSplashScreen: false
  }
};

const undefinedValue = response.settings.undefinedValue ?? 'some other default'; 
// result: 'some other default'

const nullValue = response.settings.nullValue ?? 'some other default'; 
// result: 'some other default'

const headerText = response.settings.headerText ?? 'Hello, world!'; 
// result: ''

const animationDuration = response.settings.animationDuration ?? 300; 
// result: 0

const showSplashScreen = response.settings.showSplashScreen ?? true; 
// result: false
```

<!-- wp:heading -->
<h2>No chaining with &amp;&amp; or || operators</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>It is not possible to combine both the AND (&amp;&amp;) and OR operators (||) directly with ??</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>A SyntaxError will be thrown in such cases.</p>
<!-- /wp:paragraph -->

```javascript
null || undefined ?? "supi"; // raises a SyntaxError
true || undefined ?? "supi"; // raises a SyntaxError
```

<!-- wp:paragraph -->
<p>However, providing parenthesis to explicitly indicate precedence is correct:</p>
<!-- /wp:paragraph -->

```javascript
(null || undefined) ?? "supi"; // returns "supi"
```

<!-- wp:heading {"level":3} -->
<h3>Browser Support</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>It works in recent versions of Chrome or Firefox, among others.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":804,"sizeSlug":"large"} -->
<figure class="wp-block-image size-large"><img src="http://blog.suprabha.me/wp-content/uploads/2020/07/Screenshot-2020-07-12-at-7.47.29-PM-1024x247.png" alt="" class="wp-image-804"/></figure>
<!-- /wp:image -->

<!-- wp:heading {"level":3} -->
<h3>Reference</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p><a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_Coalescing_Operator" target="_blank">MDN Nullish coalescing operator</a></p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Summary</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>The operator&nbsp;<code>??</code>&nbsp;has a very low precedence, a bit higher than&nbsp;<code>?</code>&nbsp;and&nbsp;<code>=</code>.</li><li>It’s forbidden to use it with&nbsp;<code>||</code>&nbsp;or&nbsp;<code>&amp;&amp;</code>&nbsp;without explicit parentheses.</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>I hope you find this article useful. Thanks for reading the article ❤️</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>I hope you love the article. If you have any question, please feel free to ping me on&nbsp;<strong><a rel="noreferrer noopener" href="https://twitter.com/suprabhasupi" target="_blank">@suprabhasupi</a></strong> 😋</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p></p>
<!-- /wp:paragraph -->

<table>
  <tbody>
    <tr>
      <td>
        🌟 <a href="https://twitter.com/suprabhasupi"> Twitter</a>
      </td>
      <td>
        👩🏻‍💻 <a href="https://www.suprabha.me/"> Suprabha.me</a>
      </td>
<td>
        🌟 <a href="https://www.instagram.com/suprabhasupi/"> Instagram</a>
      </td>
    </tr>
  </tbody>
</table>