Skip to content
Advertisement

Ternary shorthand for foo ? foo : bar

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?

Advertisement

Answer

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'};
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement