Nullish Coalescing operator In Javascript ES-2020 Update
NULLISH COALESCING OPERATOR is a very new operator in javascript introduced in 2020.
It was proposed back in 2018 (Read Proposal) and everyone was waiting for it to be launched finally the wait is over and with ES2020 we can use this Nullish Coalescing operator and it is extremely helpful
WHAT IS NULLISH COALESCING OPERATOR?
OR
HOW TO USE NULLISH COALESCING OPERATOR IN JAVASCRIPT?
The nullish coalescing operator (??
) is a logical operator that returns the results of the right-hand-side expression if the left-hand-side expression is either null
or undefined
SYNTAX:
leftExpr ?? rightExpr
EXAMPLE
const name = null ?? 'Kashan Haider'; console.log(name); // expected output: "Kashan Haider" const Score = 0 ?? 42; console.log(Score); // expected output: 0 const myBool= false??'Yes'; console.log(myBool); // expected output: false
COMPARING WITH ‘OR’ ( || ) OPERATOR:
From the examples above you may think that they work similarly but NO, They both works differently and in some cases, the result is completely opposite, The examples below will clear this doubt for you
let name; //variable name is never assigned any value so it is undefined. let optionalName= name || 'defaultName'; let optionalName= name ?? 'defaultName'; // expected output: 'defaultName'
In the example above you’ll get the same result because the variable name
is undefined
, It is because the OR operator is a boolean operator and for OR operator (undefined
,null
,0
,false
, NaN
, ''
) all these are falsy values. that is why the OR operator will return the string'DefaultName'
but the NULLISH COALESCING operator works only with null
& undefined
so let’s take another example how’ll it work if the variable is not undefined
or null
let num = NaN //here variabale num is NaN which is a falsy value for || operator but ?? works only with null and undefined let defaultNumber = num ?? 3 // expected output: NaN let myBool = false ?? true // expected output: false
BROWSER COMPATIBILITY
NULLISH COALESCING OPERATOR in javascript is still in development and it is not yet compatible on all browsers and is not recommended to be used in production
IMPLEMENTATION PROGRESS
Optional Chaining Operator has not yet reached cross-browser stability, It is still not fully compatible with all javascript engines.
Here’s the daily implementation of Optional Chaining Operator showing implementations on various javascript engines, this information is updated on a daily bases by Test262:
Comments
Leave a Comment