0

I realized I am using the ternary operator most of the time as following:

foo ? foo : bar;

This becomes cumbersome, as the variable length gets quite long, e. g.

appModel.settings.notifications ? appModel.settings.notifications : {};

Is there any shorthand or more elegant way of doing this? Perhaps ES6 or ES7?

uloco
  • 2,127
  • 4
  • 21
  • 34

4 Answers4

3

You can write it like this :

var foo = foo || {};
appModel.settings.notifications = appModel.settings.notifications || {};

you can also cumulate

options = default.options || foo.options || bar.options || { foo:'bar'};
Arnaud Gueras
  • 1,959
  • 10
  • 14
  • 2
    Yep, that is the "nice" behaviour of [JS logical operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators), which are evaluated from left to right. But this is quite obscure unfortunately for JS beginners… – ghybs Nov 09 '15 at 09:35
1

You can simply use non-bitwise boolean operators:

foo || bar;
bitifet
  • 3,296
  • 14
  • 33
0

When checking for nullish values we can now use the Logical Nullish Assignment:

foo ??= bar

See this answer for difference between nullish and falsy.

//these statements are the same for nullish values (null and undefined):

//falsy check
foo = foo ? foo : bar;

//falsy check
foo = foo || bar;

//nullish check
foo ??= bar;

chantey
  • 1,464
  • 14
  • 21
0

We can use in here as well, may be a bit more Human friendly, and this won't ever block.

 notifications in appModel.settings || {}
NVRM
  • 8,789
  • 1
  • 69
  • 80