Logical OR (||) vs Nullish Coalescing Operator (??) in JavaScript

WHAT TO KNOW - Aug 18 - - Dev Community

<!DOCTYPE html>











Logical OR (||) vs Nullish Coalescing Operator (??) in JavaScript



<br>
body {<br>
font-family: sans-serif;<br>
line-height: 1.6;<br>
margin: 20px;<br>
}</p>
<div class="highlight"><pre class="highlight plaintext"><code>h1, h2, h3 {
margin-top: 2em;
}

code {
font-family: monospace;
background-color: #f5f5f5;
padding: 2px 5px;
border-radius: 3px;
}

pre {
background-color: #f5f5f5;
padding: 10px;
border-radius: 5px;
overflow-x: auto;
}
</code></pre></div>
<p>








Logical OR (||) vs Nullish Coalescing Operator (??) in JavaScript





JavaScript offers various operators to handle conditional logic and data manipulation. Among these, the Logical OR (||) operator and the Nullish Coalescing Operator (??) have gained significant attention for their ability to provide default values in different scenarios. While both operators might seem similar at first glance, their underlying behavior and use cases differ considerably. Understanding these distinctions is crucial for writing robust and efficient JavaScript code.






Introduction






Logical OR (||) Operator





The Logical OR operator (||) is a fundamental part of JavaScript's boolean logic. It evaluates to true if at least one of its operands is truthy. In the context of providing default values, the OR operator returns the first truthy value it encounters. If all operands are falsy, it returns the last operand.





Here's a breakdown of how the OR operator works:



  • Truthy Values: Any value that is not explicitly considered false in JavaScript, such as numbers (except 0), strings (even empty strings), objects, and arrays.
  • Falsy Values: false, 0, -0, NaN, null, undefined, and the empty string "".




Example:







const name = "";

const greeting = Hello, ${name || "World"}!;

console.log(greeting); // Output: Hello, World!







In this example, name is an empty string, which is falsy. The OR operator evaluates to "World" because it's the first truthy value it encounters.






Nullish Coalescing Operator (??)





The Nullish Coalescing Operator (??) was introduced in JavaScript ES2020. It is designed specifically to provide a default value when the operand is either null or undefined. This operator evaluates to the first operand if it's not null or undefined, otherwise it returns the second operand.





The key difference between the OR and Nullish Coalescing operators lies in how they handle falsy values. The OR operator considers all falsy values (including 0, "", and NaN) as candidates for the default value, while the Nullish Coalescing Operator only considers null and undefined.





Example:







const age = 0;

const message = Your age is: ${age ?? "Unknown"};

console.log(message); // Output: Your age is: 0







Here, age is 0, which is falsy. However, the Nullish Coalescing Operator considers 0 a valid value, so it does not return the default "Unknown".






Key Differences



| Feature | Logical OR (||) | Nullish Coalescing (??) |

|---|---|---|

| Purpose | Provides a default value when the operand is falsy. | Provides a default value specifically when the operand is null or undefined. |

| Falsy Values | Considers all falsy values (including 0, "", NaN) as candidates for default value. | Only considers null and undefined for default value. |

| Use Cases | Best for scenarios where any falsy value should trigger the default value. | Ideal when you want to distinguish between explicit null or undefined values and other falsy values. |




Examples






Scenario 1: Handling Empty Strings





Let's say we have a form where a user can enter their username. We want to display a welcoming message that includes the username, or a generic greeting if the username field is empty. We can use either the OR or Nullish Coalescing operator for this:







// Using Logical OR

const username = "";

const greeting = Welcome, ${username || "Guest"}!;

console.log(greeting); // Output: Welcome, Guest!

// Using Nullish Coalescing

const username = "";

const greeting = Welcome, ${username ?? "Guest"}!;

console.log(greeting); // Output: Welcome, Guest!







In both cases, the username is an empty string, which is falsy. Both operators return the default "Guest" because the username is considered falsy.






Scenario 2: Distinguishing Between Zero and Undefined





Imagine you're building a shopping cart application. You want to display the total price of items in the cart. If the cart is empty, you want to show a "Cart is empty" message. However, if the cart has items but the total price is 0, you still want to display the total price as 0.







// Using Logical OR

const cartTotal = 0;

const totalPriceDisplay = Total: ${cartTotal || "Cart is empty"};

console.log(totalPriceDisplay); // Output: Total: Cart is empty

// Using Nullish Coalescing

const cartTotal = 0;

const totalPriceDisplay = Total: ${cartTotal ?? "Cart is empty"};

console.log(totalPriceDisplay); // Output: Total: 0







Here, the OR operator considers the cartTotal (0) as falsy and returns the default "Cart is empty" message. However, the Nullish Coalescing Operator correctly recognizes 0 as a valid value and displays the total price as 0.






Performance Considerations





In most cases, the performance difference between the OR and Nullish Coalescing operators is negligible. Both are optimized by JavaScript engines. However, subtle differences can arise depending on the complexity of your expressions. The OR operator might perform slightly faster in simple scenarios, as it might involve fewer checks. On the other hand, the Nullish Coalescing operator may have a slight advantage in more complex expressions, particularly when dealing with nested objects.





In general, the choice between these operators should prioritize readability and clarity over potential micro-optimizations.






Best Practices



  • Use the Nullish Coalescing Operator when you specifically want to handle null or undefined values. This is especially important when working with APIs or data sources that might return these specific values.
  • Use the Logical OR operator when you need to handle all falsy values. If you want to provide a default value for any falsy value, such as an empty string or 0, use the OR operator.
  • Prioritize readability and maintainability. Choose the operator that makes your code clearer and easier to understand, even if it involves slightly more steps.
  • Avoid excessive nesting. Keep expressions concise and readable to improve code clarity.





Conclusion





The Logical OR (||) operator and the Nullish Coalescing Operator (??) are powerful tools for providing default values in JavaScript. While they share similarities, their behavior differs significantly in how they handle falsy values. The OR operator is versatile for handling any falsy value, while the Nullish Coalescing Operator provides more targeted handling of null and undefined. Choosing the appropriate operator depends on the specific scenario and the desired behavior. By understanding these nuances, you can write more expressive and reliable JavaScript code.




. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player