Javascript: Nullish Coalescing vs OR operator

javascript:-nullish-coalescing-vs-or-operator

First of all, what is a Nullish Coalescing operator? It is the following operator: ??

Now let’s explore what it does and what is the difference between it and the OR operator.

OR operator

The OR operator || uses the right value if the left value is falsy. A falsey value is one of the following values:

  • 0, -0, 0n
  • false
  • “” (empty string)
  • null
  • undefined
  • NaN

Let’s look at examples:

// when left is falsy, the right value is used
console.log(0  || "right value") 
// Output: "right value"
console.log(false || "right value") 
// Output: "right value"
console.log(""     || "right value") 
// Output: "right value"
console.log(undefined || "right value") 
// Output: "right value"
console.log(null      || "right value") 
// Output: "right value"

// but when the left value is truthy, the left value is used
console.log(12 || "right value") 
// Output: 12

Nullish coalescing

In contrast, the Nullish coalescing operator ?? uses the right value if the left value is nullish (ie, null or undefined).

For example:

// only when the left is undefined or null that the right value is used:
console.log(undefined ?? "right value") 
// Output: "right value"
console.log(null      ?? "right value") 
// Output: "right value"

// when the left value is not nullish, then the left value is used 
console.log(0  ?? "right value") 
// Output:  0
console.log("jane" ?? "right value") 
// Output: "jane"
console.log(""     ?? "right value") 
// Output: ""
console.log(true  ?? "right value") 
// Output:  true
console.log(false ?? "right value") 
// Output:  false

Most frequently, you only want the right value if the left value is null or undefined. That’s what the nullish coalescing operator ?? is for.

Happy coding!
Mazen
My Youtube channel: @WebDevKit
My Github: @djzenma
My twitter: @djzenma

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
what-is-a-project-owner?-roles-&-responsibilities

What Is a Project Owner? Roles & Responsibilities

Next Post
looking-inside-gpt-synthesizer-and-the-idea-of-llm-based-code-generation

Looking inside GPT-Synthesizer and the idea of LLM-based code generation

Related Posts