DEV Community

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

Posted on

2 2

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay