Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript one line If...else...else if statement

I know you can set variables with one line if/else statements by doing var variable = (condition) ? (true block) : (else block), but I was wondering if there was a way to put an else if statement in there. Any suggestions would be appreciated, thanks everyone!

like image 566
Sam Perlmutter Avatar asked Mar 13 '15 22:03

Sam Perlmutter


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.

How do you write a single line in JavaScript?

Single line comments start with // . Any text between // and the end of the line will be ignored by JavaScript (will not be executed).

Can we write if-else in one line?

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.

Can you put two conditions in an if statement JavaScript?

We can also write multiple conditions inside a single if statement with the help of the logical operators && and | | . The && operators will evaluate if one condition AND another is true. Both must be true before the code in the code block will execute.


1 Answers

Sure, you can do nested ternary operators but they are hard to read.

var variable = (condition) ? (true block) : ((condition2) ? (true block2) : (else block2)) 
like image 63
Gremash Avatar answered Sep 22 '22 18:09

Gremash