Search code examples
javascriptlogical-or

When should I use ?? (nullish coalescing) vs || (logical OR)?


Related to Is there a "null coalescing" operator in JavaScript? - JavaScript now has a ?? operator which I see in use more frequently. Previously most JavaScript code used ||.

let userAge = null

// These values will be the same. 
let age1 = userAge || 21
let age2 = userAge ?? 21

In what circumstances will ?? and || behave differently?


Solution

  • The OR operator || uses the right value if left is falsy, while the nullish coalescing operator ?? uses the right value if left is null or undefined.

    These operators are often used to provide a default value if the first one is missing.

    But the OR operator || can be problematic if your left value might contain "" or 0 or false (because these are falsy values):

    console.log(12 || "not found") // 12
    console.log(0  || "not found") // "not found"
    
    console.log("jane" || "not found") // "jane"
    console.log(""     || "not found") // "not found"
    
    console.log(true  || "not found") // true
    console.log(false || "not found") // "not found"
    
    console.log(undefined || "not found") // "not found"
    console.log(null      || "not found") // "not found"
    

    In many cases, you might only want the right value if left is null or undefined. That's what the nullish coalescing operator ?? is for:

    console.log(12 ?? "not found") // 12
    console.log(0  ?? "not found") // 0
    
    console.log("jane" ?? "not found") // "jane"
    console.log(""     ?? "not found") // ""
    
    console.log(true  ?? "not found") // true
    console.log(false ?? "not found") // false
    
    console.log(undefined ?? "not found") // "not found"
    console.log(null      ?? "not found") // "not found"
    

    While the ?? operator isn't available in current LTS versions of Node (v10 and v12), you can use it with some versions of TypeScript or Node:

    The ?? operator was added to TypeScript 3.7 back in November 2019.

    And more recently, the ?? operator was included in ES2020, which is supported by Node 14 (released in April 2020).

    When the nullish coalescing operator ?? is supported, I typically use it instead of the OR operator || (unless there's a good reason not to).