54

I have some logic that switches(with and else/if) true/false with on/off but I would like to make is more condensed and not use a switch statement. Ideally the if/else would be converted into something that is one short line. Thank you!!!

var properties = {};
var IsItMuted = scope.slideshow.isMuted();
if (IsItMuted === true) {
    properties['Value'] = 'On';
} else {
    properties['Value'] = 'Off';
}       
scniro
  • 16,844
  • 8
  • 62
  • 106
Scott
  • 617
  • 1
  • 5
  • 7

4 Answers4

106

You want a ternary operator:

properties['Value'] = (IsItMuted === true) ? 'On' : 'Off';

The ? : is called a ternary operator and acts just like an if/else when used in an expression.

elixenide
  • 44,308
  • 16
  • 74
  • 100
20

You can likely replace your if/else logic with the following to give you a "one-liner"

properties['Value'] = scope.slideshow.isMuted() ? 'On' : 'Off';

see Conditional (ternary) Operator for more info

scniro
  • 16,844
  • 8
  • 62
  • 106
9
var properties = {"Value":scope.slideshow.isMuted() && "on" || "off"}
guest271314
  • 1
  • 15
  • 104
  • 177
7

Combine all into one line.

You don't need to create empty object, it can have properties and if brevity is what you want don't need the isItMuted either

var properties = {Value : scope.slideshow.isMuted() ? 'On' : 'Off'};
charlietfl
  • 170,828
  • 13
  • 121
  • 150