Nullish Coalescing Operator (??) in Javascript

Nullish Coalescing Operator (??) in Javascript

ยท

2 min read

The Nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined and otherwise returns its left-hand side operand.

const userName = null ?? 'prathmesh';
console.log(userName);
// expected output: "prathmesh"

Syntax

leftExpr ?? rightExpr

Why JavaScript Needed the Nullish Coalescing Operator

Earlier, when one wanted to assign a default value to a variable, a common pattern was to use the logical OR operator ||

let defaultUser;
let someDummyText = defaultUser || 'Admin';
console.log(someDummyText)
// expected output: "Admin"

But, due to || being a boolean logical operator, It considers all false values (0, '' " (empty string), NaN, null, undefined, false). This behavior may cause unexpected consequences if you consider 0, '' " (empty string), or NaN as valid values.

The || operator works great but sometimes we only want the next expression to be evaluated when the first operand is only either null or undefined.

Therefore, ES11 has added the nullish coalescing operator.

Let's see the Difference between || and ?? through example

let num = 0
console.log( num || 10 )     //output = 10
console.log( num ?? 10 )     //output = 0   

let text = ""
console.log (text || "Hello from || operator" )   //output = Hello from || operator
console.log (text ?? "Hello from ?? operator " )  //output = ""

Short-Circuiting

Like the OR and AND logical operators, the right-hand side expression is not evaluated if the left-hand side proves to be neither null nor undefined.

let num1
let num2 = 10;
const example = () => "example called"
console.log( num1 ?? example() ) // example called
console.log( num2 ?? example() ) // 10

Woooo! Thank you for reading ๐Ÿ˜„

giphy.gif

Feel Free the comment your thoughts or and doubts ๐Ÿ‘‡

ย