DEV Community

Cover image for Javascript: Nullish Coalescing vs OR operator
Mazen
Mazen

Posted on

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)