Tuesday Coding Tip 11 — null-coalescing operator

posted Originally published at medium.com 1 min read

Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.


Some languages, like C# or Javascript, have a special operator ?? which is a specialization over the normal ternary operator. It either returns the value of the left operand or, if it is null, it returns the value of the right operand.

Furthermore, the ??= operator allows you to only assign to a variable if it is null. Syntax among languages might differ, so check out this overview: https://en.wikipedia.org/wiki/Null_coalescing_operator

var a = null;

// Initialize b with a, or with 42 if a is null
var b;
if (a == null) b = 42;
else b = a;

// Shorter version with ?? operator
var c = a ?? 42;

// Update a with something if it is null
a ??= 24;

1 Comment

2 votes

More Posts

Tuesday Coding Tip 02 - Template with type-specific API

Jakub Neruda - Mar 10

Tuesday Coding Tip 06 - Explicit template instantiation

Jakub Neruda - Apr 7

TypeScript Complexity Has Finally Reached the Point of Total Absurdity

Karol Modelskiverified - Apr 23

Your Tech Stack Isn’t Your Ceiling. Your Story Is

Karol Modelskiverified - Apr 9

I’m a Senior Dev and I’ve Forgotten How to Think Without a Prompt

Karol Modelskiverified - Mar 19
chevron_left

Related Jobs

View all jobs →

Commenters (This Week)

10 comments
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!