The nullish-coalescing operator

Posted on

In JavaScript, we can use || to set default values for variables. This operator returns the first value if it is truthy and the second value otherwise.

Unfortunately, this does not only override null and undefined. It also overrides other falsy values like 0, false, and empty strings. Sometimes, these are valid values we want to keep.

The nullish-coalescing operator ?? only overrides null and undefined. It leaves all other falsy values intact.

       27 || "default"    // ⇒ 27           good
     true || "default"    // ⇒ true         good
"truthy!" || "default"    // ⇒ "truthy!"    good
     null || "default"    // ⇒ "default"    good
undefined || "default"    // ⇒ "default"    good
        0 || "default"    // ⇒ "default"    bad (overrides real value)
    false || "default"    // ⇒ "default"    bad (overrides real value)
       "" || "default"    // ⇒ "default"    bad (overrides real value)
 
       27 ?? "default"    // ⇒ 27           good
     true ?? "default"    // ⇒ true         good
"truthy!" ?? "default"    // ⇒ "truthy!"    good
     null ?? "default"    // ⇒ "default"    good
undefined ?? "default"    // ⇒ "default"    good
        0 ?? "default"    // ⇒ 0            good (keeps real value)
    false ?? "default"    // ⇒ false        good (keeps real value)
       "" ?? "default"    // ⇒ ""           good (keeps real value)
       27 || "default"    // ⇒ 27           good
     true || "default"    // ⇒ true         good
"truthy!" || "default"    // ⇒ "truthy!"    good
     null || "default"    // ⇒ "default"    good
undefined || "default"    // ⇒ "default"    good
        0 || "default"    // ⇒ "default"    bad (overrides real value)
    false || "default"    // ⇒ "default"    bad (overrides real value)
       "" || "default"    // ⇒ "default"    bad (overrides real value)
 
       27 ?? "default"    // ⇒ 27           good
     true ?? "default"    // ⇒ true         good
"truthy!" ?? "default"    // ⇒ "truthy!"    good
     null ?? "default"    // ⇒ "default"    good
undefined ?? "default"    // ⇒ "default"    good
        0 ?? "default"    // ⇒ 0            good (keeps real value)
    false ?? "default"    // ⇒ false        good (keeps real value)
       "" ?? "default"    // ⇒ ""           good (keeps real value)
Debug
none
Grid overlay