I usually run into writing conditionals like this and I'm wondering if there a short hand way to write something similar below without calling a function
const currentValue = this.props.book.location.areaValueInDollars ? this.props.book.location.areaValueInDollars : 0;
CodePudding user response:
Use nullish coalescing operator:
this.props.book.location.areaValueInDollars || 0
More on the subject here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
CodePudding user response:
You can use short-circuiting and the Logical OR operator.
const currentValue = window['a'] || 0;
console.log(currentValue);
If the variable exists, then the first operand will return true
, causing it to "short circuit" and be returned. The second operand is only evaluated if the first is false
, since the expression is evaluated from left to right.
Using the Logical OR operator has a caveat though. If the variable is 0
, null
, undefined
... (for full list, see Falsy values), it will return false.
To solve this, we can use the Nullish coalescing operator, which will only return the right-hand side operand if the left operand is null
or undefined
. Like so:
const currentValue = window['a'] ?? 0;
console.log(currentValue);