ECMAScript 2020 has a new operator for managing undefined and null values: ??. The ECMAScript 2020 specification has a new operator for managing undefined or null values. The null coalescing operator will take an initial variable/expression/statement and attempt to use it.
In the event that it is either undefined or null, the second operand, appearing after the ??, will be used as a fallback.

Examples of how to use the Null Coalescing
Below is a rundown of basic data types and how they evaluate using the ?? operator.

const a;
const b = null;
const c = "";
const d = 0;
const e = false;
const testArray = [];

const t1 = a ?? "Default Value";  // "Default Value"
const t2 = b ?? "Default Value";  // "Default Value"
const t3 = c ?? "Default Value";  // ""
const t4 = d ?? "Default Value";  // 0
const t5 = e ?? "Default Value";  // false
const t6 = testArray[1] ?? "Default Value";  // "Default Value"

Null Coalescing Operator vs. Logical “or” Operator

The logical “or” short circuit operator ||, which behaves the same as the Elvis Operator, is used to reconcile two values similar to the null coalescing operator. The difference is in the rules to determine if the first operand is used.

The logical “or” will coerce the first operand as a boolean and only use it when evaluating true. This would exclude the number zero as well as empty strings, objects, and arrays.

The null coalescing operator specifically looks for an undefined or null value in the first operand as the requirement for deferring to the second.

let a = 0;
let b = 7;
// Logical Or Behavior
console.log(a || b);  // 7
// Null Coalescing Behavior
console.log(a ?? b);  // 0

We can write them out as analogous ternary operator statements to more clearly see the difference.

let a = 0;
let b = 7;
let logical_or = (a) ? a : b;
console.log(logical_or); // 7
let nc = (typeof a == "undefined" || a == null) ? b : a;
console.log(nc);    // 0

We hope this tutorial was useful in explaining the null coalescing operator and you can get more comfortable using it in your applications.



Discover Batch and API Geocoding Excellence

Experience unmatched flexibility and accuracy in geocoding, all in one platform. Connect with Geocodify today and redefine your geospatial capabilities.