Does JavaScript have an equivalent to the null coalescing operator?

I’m wondering if JavaScript has something similar to the null coalescing operator that exists in other programming languages.

In C#, you can write code like this:

string myText = null;
var result = myText ?? "Default value!";

Right now in JavaScript, I’m using the ternary operator to achieve similar functionality:

var myText = null;
var result = myText ? myText : 'Default value!';

This approach works but feels a bit clunky to me. Is there a cleaner or more elegant way to handle null values in JavaScript? I’d appreciate any suggestions for better alternatives.

The Problem:

You’re looking for a cleaner way to handle null values in JavaScript, similar to the null coalescing operator (??) in C#. You’re currently using the ternary operator, but find it clunky.

TL;DR: The Quick Fix:

Use the nullish coalescing operator (??) introduced in ES2020. It provides a concise and efficient way to handle null or undefined values.

var myText = null;
var result = myText ?? 'Default value!'; 

This will assign ‘Default value!’ to result only if myText is null or undefined. Otherwise, it will assign the value of myText.

:thinking: Understanding the “Why” (The Root Cause):

The ternary operator (condition ? value_if_true : value_if_false) works, but it’s not ideal for handling only null and undefined values because it considers other “falsy” values (like 0, false, "", NaN) as false. The ?? operator is specifically designed to check for null or undefined and only then provide a default value. This makes your code more precise and less prone to unexpected behavior.

The nullish coalescing assignment operator (??=) is also very useful:

let myVar; // undefined
myVar ??= "default"; // myVar becomes "default"

let otherVar = ""; // falsy, but not nullish
otherVar ??= "another default"; // otherVar remains ""

:mag: Common Pitfalls & What to Check Next:

  • Difference between ?? and ||: Don’t confuse ?? with the logical OR operator (||). || considers any falsy value as false, while ?? only checks for null and undefined. This subtle difference can lead to unexpected results. Using || when you need to handle only nullish values can introduce bugs.

  • Browser Compatibility: While widely supported in modern browsers, for older browsers, you might need a transpiler like Babel to ensure compatibility. However, most modern bundlers handle this automatically.

  • Chaining with Optional Chaining: You can combine the nullish coalescing operator with optional chaining (?.) for elegant handling of deeply nested objects where some properties might be null or undefined:

const address = user?.address?.street ?? 'Unknown Street';

:speech_balloon: Still running into issues? Share your (sanitized) config files, the exact command you ran, and any other relevant details. The community is here to help!

your ternary logic’s backwards btw - should be myText ? myText : 'default' but that’ll still fail on empty strings. ?? is def the way to go for proper null checking.

Just want to add that while ?? is perfect for modern environments, you’ll also see the logical OR operator || in older codebases doing similar things. But there’s a key difference that trips up tons of developers. The || operator treats all falsy values as triggers for the default, while ?? only cares about nullish values. I learned this the hard way when refactoring form validation code - empty strings kept getting replaced with defaults unexpectedly. If you’re stuck with legacy code or need broader browser support, you can use a simple function approach or even the old typeof myText !== 'undefined' && myText !== null check. The nullish coalescing operator is definitely the cleanest solution though, and most bundlers handle backwards compatibility automatically now.

Yes, the nullish coalescing operator ?? is exactly what you need. It was added in ES2020 and works just like C#'s version. javascript var myText = null; var result = myText ?? 'Default value!'; The big advantage over your ternary approach? ?? only checks for null and undefined, while || also triggers on empty strings, zero, or false values. Your current ternary example actually has a bug - it’ll return ‘Default value!’ even when myText is an empty string or 0, which probably isn’t what you want. I’ve been using ?? tons since migrating legacy codebases to modern JavaScript. Super useful when dealing with API responses where you need to tell the difference between intentionally falsy values and actual null/undefined states. Browser support is solid across all modern browsers now, though you’ll need a transpiler for older environments.

This topic was automatically closed 6 hours after the last reply. New replies are no longer allowed.