Nullish Coalescing operator in JavaScript

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.


Here's a way using es6 destructuring and defaults:

const {
  updateItem: {
    unit = 'Unit'
  } = {}
} = this.state;

then you can just use unit

Tags:

Javascript