AND / OR operators, Short-Circuiting and Nullish Coalescing in Javascript
Tags: webdev, javascript, logicalgates, operators
Published: 2024-06-04 16:16:26

## Introduction  
Short Circuiting and Nullish Coalescing are mechanisms available in javascript to enhance code efficiency and readability, by providing special way of evaluating values.  
It relies on the logical operators `&&` and `||`, while nullish Coalescing relies on the  operator `??`, Both tools are powerful, but have to be used in the right context to shine  
  
## A detailed comparaison  
  
Get some coffee and buckle up, we're going full technical.  
  
## Short-Circuiting  
  
Short-Circuiting Applies to the logical operators `&& (AND)` and `|| (OR)` in JavaScript, But these operators originate from a neighbour field of science: Logical Gates in Electronics  
  
## Logic Gates  
  
### Logical Gate AND  
  
In Electronics Engineering, The AND logical gate is nothing more but a circuit that represents the boolean logic:  
`A.B` meaning `A and B`, which is written in programming as `A && B`  
  
Let's Imagine two switches connected in series with a light bulb; For the bulb (output) to light up `1 / ON / Truthy`, both switches (inputs) need to be closed `1 / ON / Truthy`.  
If either switch is open `0 / OFF / Falsy`, the circuit is broken, and the bulb stays `off (0)`.  


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m4rvmd0cu5e0w4gszi34.png)

Now if we consider the light bulb to be Q , Q will only evaluate to true if both A and B allow the current to pass through, else Q will be falsy.  
  
Therefore, the expression `A + B = Q` will only evaluate to 1(true) if  A=1 and B=1, which is illustrated by what is called in electronics: a truth table.  
  

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/962daz5p35sfxp8phlwx.png)


  
### Logical Operator  AND  
The expression might differ in programming, but the logic is the same, Q will only be truthy if both A and B are truthy  
  
```javascript  
// AND operator  
Q = A && B // A and B Must Have truthy values in order for Q to be truthy  
  
// Similar example using only if statement  
if (!A) {  
 Q = false;} else if (!B) {  
 Q = false;} else {  
 Q = true;}  
```
  
  
### Logical Gate OR  
Similarly to the AND gate, the OR gate will represent a boolean logic, the Boolean logic for an OR circuit is represented by the plus symbol `+ (OR)`. So, for an OR circuit, the Boolean logic expression would be:  
`A + B` which means `A OR B`, which is written in programming as `A || B`  
  
Let's revisit our previous light bulb example, If either switch (input) is `closed (1)`, the light (output) turns `on (1)`. Only when both switches are `open (0)` will the light stay `off (0)`.  
  
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h0hf6yqp1639963cyn8d.png)


The logic or Boolean expression for an OR gate is `A+B = Q` which means: If `A or B` is true, then Q is true, below is the truth table for an `OR gate`.  


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0kl3467z26c2omli0gkd.png)


  
### Logical Operator OR  
  
```javascript  
// OR operator  
Q = A || B // A OR B Must be truthy in order for Q to be truthy  
  
// Similar example using only if statement  
if (A) {  
 Q = true;} else if (B) {  
 Q = true;} else {  
 Q = false;}  
```  
  
  
### The Why to Logical Operators  
  
As seen in the precious examples, logical operators are cleaner and shorter to write but that's not convincing enough right ?  
  
When evaluating an expression involving these operators, JavaScript only evaluates one side of the expression if necessary, which is a big win in performance when evaluating conditions that come with costly operations to resolve;  
 - For && (AND):  
    - If the left side is false, the entire expression is false without evaluating the right side.  
 - For || (OR):  
    - If the left side is true, the entire expression is true without evaluating the right side.  
  
*Example:*  
  
```javascript  
const isLoggedIn = true;  
const hasPremium = true;  
const isAdmin = false;  
const isGuest = false;  
  
const canViewPremium = isLoggedIn && hasPremium //canViewPremium = true  
const canViewAdmin = isLoggedIn && isAdmin //canViewAdmin = false  
const canNavigate = isLoggedIn || isGuest // will default to true because isLoggedIn is true  
```
  
- we can also use logical operators for conditional execution of functions 

```javascript  
const isLoggedIn = true;  
const isAdmin = false;  
const hasPremium = true;  
  
isLoggedIn && RedirectToHome() //the function will be executed  
isAdmin && isLoggedIn && RedirectToAdminPanel() //the function will not be executed  
 (isLoggedIn && (isAdmin || hasPremium)) && RedirectToPremium() //the function will be executed 
``` 
  
  
- one more use case for logical operators is fallback values or default values using the OR operator.  
- these come in handy when dealing with values that could be falsy: `undefined, null, false, 0, Empty string` (pay attention to what we are considering falsy in here) 

```javascript  
const user = {}  
const isAdmin = user.isAdmin || false // if user.isAdmin is not defined, isAdmin defaults to false  
```
  
  
  
## Nullish Coalescing Operator (??) (Introduced in ES2020)  
  
The Nullish Coalescing Operator was introduced to complement the logical OR operator by providing a way to assign a default value ONLY if the left operand is null or undefined.  
It obviously differs from `|| (OR)`, because `||(OR)` considers all falsy values (including false, 0, and an empty string "") as equivalent to null or undefined, while `??` considers only `null and undefined` to be falsy  
  
*Example:*  

```javascript  
let user = {  
 name: ''};  
let name1 = user.name || "Default User"; // name1 will be Default User  
let name2 = user.name ?? "Default User"; // name2 will be ''  
  
let maybeValue = 0;  
let result = maybeValue ?? 10; // 'result' will be 0 (falsy but not null/undefined)  
```  
  
*Key Points:*  
  
| Feature            | Behavior                                             |  
|--------------------|------------------------------------------------------|  
| Short-Circuiting   | Optimizes evaluation of logical expressions          |  
| Nullish Coalescing | Assigns default value specifically for null/undefined |  
| OR Operator        | Considers all falsy values as equivalent to null/undefined|  
  
*When to Use:*  
  
- Use short-circuiting for conditional logic where you only need to evaluate one side of the expression based on the other side's truthiness/falsiness.  
- Use nullish coalescing when you want to provide a default value only for null or undefined cases, and other falsy values should retain their meaning.  
  
* Additional Ressources *  
  
[Short Circuiting and Nullish-Coalescing Operators](https://medium.com/@rabailzaheer/short-circuiting-and-nullish-coalescing-advanced-techniques-ad453b6a385a#:~:text=In%20summary%2C%20short%2Dcircuiting%20and,when%20dealing%20with%20falsy%20values.).