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?
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.
JavaScript now supports the nullish coalescing operator (??). It returns its right-hand-side operand when its left-hand-side operand is null or undefined , and otherwise returns its left-hand-side operand. Please check compatibility before using it.
In JavaScript, a nullish value is the value which is either null or undefined . Nullish values are always falsy.
The JavaScript double question mark (??) operator is called the nullish coalescing operator and it provides a default value when a variable or an expression evaluates to null or undefined.
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
You can try with setting empty object as default value:
(this.state.updateItem || {}).unit || 'Unit'
unit will always either have value or be undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With