1

I have a use case where I'm showing data from an API. If there is no data for that field, I'm showing a hyphen. in some cases where API returns 0 as a value, the UI would still show a hyphen.

const value = APIValue || '-'

In the above case, How do we show 0 instead of the hyphen when the input is 0?

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
visizky
  • 701
  • 1
  • 8
  • 27
  • Either use an actual condition or use the nullish coalescing operator `??` instead of `||`. I recommend the latter. – VLAZ Oct 03 '20 at 09:52
  • Does this answer your question? [Is there a "null coalescing" operator in JavaScript?](https://stackoverflow.com/questions/476436/is-there-a-null-coalescing-operator-in-javascript) – VLAZ Oct 03 '20 at 09:53
  • What type of values can you receive from that api? – Elanochecer Oct 03 '20 at 09:53
  • @VLAZ, 0 ? 'True' : 'False' will always return false. – visizky Oct 03 '20 at 09:54
  • @Elanochecer, API always returns a number. – visizky Oct 03 '20 at 09:55
  • 1
    @visizky but `typeof value === "number" ? value : "-"` doesn't. As I said, using an *actual condition* - that isn't testing the truthiness of the value. – VLAZ Oct 03 '20 at 09:56
  • This would work if I don't change the API response value's type. In the case where API resp type for value would vary, it would always show hyphen. – visizky Oct 03 '20 at 09:59
  • OK, then make the condition whatever will match your API data. I am no longer sure what you're looking for - apparently you want a condition that somehow knows what your data is and forever would be and chooses the appropriate representation? Is it really impossible to do `value != null ? value : "-"` or what? – VLAZ Oct 03 '20 at 10:02

4 Answers4

1

You can use either isNan or type checking the variable if you are expecting a number:

const APIValue = 0;
const value = !isNaN(APIValue) ? APIValue : '-'

console.log(value)

const APIValue = 0;
const value = typeof APIValue === "number" ? APIValue : "-";
console.log(value)

If you just want the variable to have any value you should check if its null, since this captures also undefined values:

const APIValue = 0;
const value = APIValue != null ? APIValue : "-";
console.log(value)
Elanochecer
  • 600
  • 3
  • 8
1

You can use a ternary operator:

const value = APIValue || ((APIValue === 0) ? 0 : '-')
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
0

Either use null coalescing operator or add if like one below:

If(APIValue === 0)
     return 0;
else
     return APIValue || '-'
Piyush Rana
  • 631
  • 5
  • 8
0

Try this:

const value = (APIValue == null ? '' : APIValue.toString()) || '-';