Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One line if/else in JavaScript [duplicate]

Tags:

javascript

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'; }        
like image 798
Scott Avatar asked May 12 '15 00:05

Scott


People also ask

How do you write one-line if-else in JavaScript?

Writing a one-line if-else statement in JavaScript is possible by using the ternary operator. Running this code prints “Adult” into the console. This code works fine. But you can make it shorter by using the ternary operator.

Can you have multiple else if statements JavaScript?

JavaScript will attempt to run all the statements in order, and if none of them are successful, it will default to the else block. You can have as many else if statements as necessary. In the case of many else if statements, the switch statement might be preferred for readability.

Can I use && in if statement in JavaScript?

In the logical AND ( && ) operator, if both conditions are true , then the if block will be executed. If one or both of the conditions are false , then the else block will be executed.

How do you write an if-else in one-line in Python?

Writing a one-line if-else statement in Python is possible by using the ternary operator, also known as the conditional expression. This works just fine. But you can get the job done by writing the if-else statement as a neat one-liner expression.


1 Answers

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.

like image 83
elixenide Avatar answered Sep 20 '22 16:09

elixenide