Coalesce in JavaScript
IMHO, one of the most underused operators in C# is the coalesce operator (??). If you’re not familiar with this operator, it allows you to perform a ternary-like operation testing against a null reference object. Essentially, it’s a shortcut that returns the left-hand side of the coalescing operator if it’s non-null, or the right hand side if it is null.
Here is an example…
string foo = "foo"; string emptyString = ""; string nullify = null; string testFoo = foo ?? "foo must have been null"; // testFoo = "foo" string someString = emptyString ?? "something"; // someString = ""; string testNullify = nullify ?? "nullify must have been null"; // test Nullify = "nullify must have been null"
JavaScript does not have a coalesce operator per se, but idiomatically it does have a equivalent. Before we dive into that, let’s back up and discuss how JavaScript handles conditional tests.
In addition to the traditional boolean values of “true” and “false”, JavaScript has the concept (as Doug Crockford calls them) of “truthy” and “falsy” values. These values don’t map exactly as what a C# developer might expect them to do so since they’re not exactly explicitly 0 or 1.
Here are the values JavaScript considers “falsy” (taken directly from JavaScript: The Good Parts):
- false
- null
- undefined
- The empty string ”
- The number 0
- The number NaN
All these values, when evaluated in a boolean conditional test, will return false. Everything else is considered a “truthy” value – but doesn’t necessarily return true.
In JavaScript, when using the || operator, the return value is: 1) the value of the first operand (i.e. not necessarily “true”) if it is “truthy”; or 2) the value of the second operand. So in order to return false from an or expression in JavaScript, but sides of the expression must be “falsy” values.
Idiomatically, JavaScript developers use the || operator as a de facto coalescing operator. It is probably confusing to a traditional C-based language developer, but here is how it looks:
var foo = "foo"; var emptyString = ""; var nullify; // null var testFoo = foo || "foo must be null"; // testFoo = "foo" var someString = emptyString || "something"; // someString = "something"; var testNullify = nullify || "nullify must be null"; // test Nullify = "nullify must have been null"
So you can use the || operator as a way to initialize objects by comparing it against a “falsy” value. Think of it as a way to create an object using a default value if one is not already set. Indeed, this is one of the main ways JavaScript developers use it.
If you are a C# developer, this operator might not make immediate sense. But once you understand the “truthy” and “falsy” values in JavaScript, you are on your way to writing great JavaScript code.
