Conditional Assignment (null coalescing)

Posted on

Thought I’d share one of my favorite language features (of any language that has it): conditional assignment, sometimes called null coalescing. Here’s a few versions of it:

C#:

 var a = ( b??c); // a = b if b is truthy, c if b is falsey
 // or:
(b ?? c).callMethod(); // nice!

javascript:

var a = b || c;
(b || c).callMethod(); 

python/ruby:

 a = b || c 
// lower precedence (i.e. only if b isn't defined, not "falsey")
a = b or c

php:

$a = b || c;
$a = b or c; // just like python

Leave a Reply

Your email address will not be published. Required fields are marked *