DEV Community

Cover image for TS: Nullish Coelescing (The TS Ternary Shortcut)
Anthony Petrides
Anthony Petrides

Posted on

TS: Nullish Coelescing (The TS Ternary Shortcut)

Nullish Coelescing in TypeScript is practically a shortcut for the ternary operator, achieved by using ?? between statements or values.

The double question marks work from left to right. Take the basic example below:

const value1 = undefined;
const value2 = 6;

const result = value1 ?? value2;

console.log(result); // returns 6
Enter fullscreen mode Exit fullscreen mode

This reads as follows:

"If value1 is not null or undefined and has an actual value, then return that value. However, if value1 does not have a value, then return value2"

It's important to note that in the case of nullish coelescing, only null or undefined are being checked specifically. This should not be confused with checking for "truthyness" like the logical || operator would.

Take the below examples as a final explanation on this:

const b = "" ?? 42;
console.log(b); // returns ""

const c = false ?? 42;
console.log(c); // returns false

const d = NaN ?? 42;
console.log(d); // returns NaN

const e = -0 ?? 42;
console.log(e) // returns -0
Enter fullscreen mode Exit fullscreen mode

Top comments (0)