16

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?

5 Answers 5

23

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

1
  • Thanks for figuring out! Yea I think it will be great to do such thing Commented Dec 10, 2017 at 7:31
5

You can try with setting empty object as default value:

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

unit will always either have value or be undefined.

0
2

Here's a way using es6 destructuring and defaults:

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

then you can just use unit

1
  • Thank you for your suggestion but i'm looking for inline answer Commented Dec 10, 2017 at 7:32
1

The previous answers to this question are no longer relevant.

As of mid-2020 a Nullish Coalescing Operator was added to the official ECMAScripts. It is a true Nullish Coalescing Operator in the sense that it behaves as you would expect a Nullish Coalescing Operator too behave. The JavaScript syntactical implementation of the operator was derived from a syntax that is used by several other programming languages, therefore, experienced veteran developers are likely to be familiarized with it, even if they have never used it while writing JavaScript.

const varAlpha = varBeta ?? varGamma;

"The Nullish-Coalescing Operator returns the value of varBeta if varAlpha is not null, and is not undefined, otherwise it returns varGamma."



Evaluating the Nullish Coalescing Operator:

let varAlpha =  varBeta ?? varGamma;

// Equates to:

let varAlpha =  (varBeta !== null && varBeta !== undefined) 
    ? varBeta
    : varGamma;

0

You can do something like this.

const path = (pathString, obj) =>
  pathString.split(".")
    .reduce((obj = {}, key) => obj[key], obj);

const defaultTo = (x, y) => y == null ? x : y;

// in your own code
const unit = defaultTo(
  "Unit",
  path("state.updateItem.unit", this)
);

These functions already exist in ways similar to this, inside of libraries like ramda or lodash/fp.

It also lessens the need for obj?.state?.updateItem?.unit everywhere, though it's clearly not perfect.

Not the answer you're looking for? Browse other questions tagged or ask your own question.