Javascript Null Coalescing Operator ??

 ← Dev Articles
👍 0
👎 0

The double question mark ?? in javascript is referred to as the null coalescing operator.  It was introduced in JavaScript ES2020.  It allows you to check for null or undefined variable.   In most cases the order of operation for this operator follows the math and comparison operators.  Below are a few examples: 


Example 1:
let myval = null;
console.log(myval ?? 20); // output is 20 because myval is null

Example 2:
console.log(myval ?? 20); // output is 20 because myval is undefined

Example 3:
let myval = [];
console.log(myval ?? [1,2,3]);  // output is [] because it isn't null and it's not undefined

If the myval is anything other than null or undefined, the output will be the value of the right-hand side of the equation.