8

We have the Null coalescing operator in .NET and we can use as below

string postal_code = address?.postal_code;

Same thing can we do in React JS?

What i found like we can do with && operator

in address.ts file

string postal_code = address && address.postal_code;

what i need like .net feature is possible in typescript with react JS, is that possible ?

something like:

string postal_code = address?.postal_code // I am getting the error in this line if I try to use like .NET
Fateme Fazli
  • 11,582
  • 2
  • 31
  • 48
Praveen Kumar
  • 1,966
  • 1
  • 9
  • 16

2 Answers2

6

This is a proposed feature in TypeScript, under the legendary Issue #16

It won't be introduced into TypeScript until the ECMAScript spec for this feature is firm as there is a desire for the TypeScript implementation to follow that specification - so you'll get it early, but not massively early in this case.

It is referred to as any of the following:

  • Null Propagation Operator
  • Existential Operator
  • Null Coalesce Operator
Fenton
  • 241,084
  • 71
  • 387
  • 401
  • Any update on this? Looks like the issue is still locked. Also, are there any efficient workarounds for the time being? – Trevor Mar 04 '19 at 18:58
  • The "null coalesce" operator is the [related-but-different](https://github.com/tc39/proposal-nullish-coalescing) `??` operator. Also both of these proposals recently went to stage 2, so hopefully it will be implemented soon! – Dave Jul 07 '19 at 11:33
5

Update in 2020: The nullish-coalescing operator mentioned below is now through the process and in ES2020, as is the optional chaining operator that lets you do:

let postal_code = address?.postal_code;
// −−−−−−−−−−−−−−−−−−−−−−^

With optional chaining, if address is null or undefined, postal_code will get undefined as its value. But if address is neither null nor undefined, postal_code will get the value of address.postal_code.


JavaScript doesn't have a null-coalescing operator (nor does TypeScript, which mostly limits itself to adding a type layer and adopting features that are reasonably far along the path to making it into JavaScript). There is a proposal for a JavaScript null-coalescing operator, but it's only at Stage 1 of the process.

Using the && idiom you've described is a fairly common approach:

let postal_code = address && address.postal_code;

If address is null (or any other falsy¹ value), postal_code will be that same value; otherwise, it will be whatever value address.postal_code was.


¹ The falsy values are 0, "", NaN, null, undefined, and of course false.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875