JavaScript – Understanding Nullish Coalescing Operator

javascript

How to this thing in better way.

this.state.updateItem?this.state.updateItem.unit:'Unit';

I have tried with this.state.updateItem.unit || 'Unit', but it found out that it will produce error since this.state.updateItem is NULL then it can't find any property of unit.

How to do it in better way?

Best Answer

For now you have to do this like:

(this.state.updateItem || {}).unit || 'Unit'

There is a stage one proposal to ES (JavaScript) for optional chaining whereby we'll (eventually, hopefully) be able do do something like this:

this.state.updateItem?.unit || 'Unit'

And if you're doing babel you can use it now!:
https://www.npmjs.com/package/babel-plugin-transform-optional-chaining

Edit: The proposal is now in stage 4 (as of January 2020) and will be added into the JavaScript standard

Related Question