1

I have a lot of thoses in my code

somevale.get() ? somevale.get() : "my default value"

is there a way to simplify it, I would like the following syntax wich is equivalent to the version on top

somevale.get() ?: "my default value"

or at least something like

somevale.get() ? default: "my default value"

I know I could build it myself easyli

function check(value,default)
...

but I would like to avoid it. Is there any other option?

Xanlantos
  • 887
  • 9
  • 18
  • [What does the construct x = x || y mean?](https://stackoverflow.com/q/2802055) | [Javascript AND operator within assignment](https://stackoverflow.com/q/3163407) | [Is there a “null coalescing” operator in JavaScript?](https://stackoverflow.com/q/476436) | [Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?](https://stackoverflow.com/q/6613952) – VLAZ Nov 13 '20 at 17:05

2 Answers2

4

You could use somevale.get() || "my default value".

Rob Bailey
  • 920
  • 1
  • 8
  • 23
3

I would go with the following:

somevale.get() ||  "my default value"

or

somevale.get() ??  "my default value"

First one is logical OR of JavaScript, which has rules for strings and numbers, that if first value is treated falsy (empty, undefined, null, zero) the default is used.

Second one is a newbie from ECMA 2020 which treats only undefined and null worthy for default value. It is safer, logical OR causes problems if first value is a boolean.

On other hand, you may need to wait a little that your ECMA 2020 code works properly on current browsers. It may take time all new features are available.

More info:

Is there a "null coalescing" operator in JavaScript?

https://medium.com/better-programming/how-to-use-the-null-coalescing-operator-in-javascript-15adefe7c655

ES7, ES8, ES9, ES10 Browser support

mico
  • 12,730
  • 12
  • 59
  • 99