Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorthand for if-else statement

I have some code with a lot of if/else statements similar to this:

var name = "true";  if (name == "true") {     var hasName = 'Y'; } else if (name == "false") {     var hasName = 'N'; }; 

But is there a way to make these statements shorter? Something like ? "true" : "false" ...

like image 468
Meek Avatar asked Aug 16 '13 08:08

Meek


People also ask

What is shorthand if else in Python?

Shorthand if else is one such feature using which you can write if else statement in one line of code. The format of shorthand if else is: statement1 if condition else statement2. If the condition evaluates to True, then statement 1 will execute; otherwise, statement2 will run.

What is the alternative of if else?

The Ternary Operator One of my favourite alternatives to if...else is the ternary operator. Here expressionIfTrue will be evaluated if condition evaluates to true ; otherwise expressionIfFalse will be evaluated. The beauty of ternary operators is they can be used on the right-hand side of an assignment.


1 Answers

Using the ternary :? operator [spec].

var hasName = (name === 'true') ? 'Y' :'N'; 

The ternary operator lets us write shorthand if..else statements exactly like you want.

It looks like:

(name === 'true') - our condition

? - the ternary operator itself

'Y' - the result if the condition evaluates to true

'N' - the result if the condition evaluates to false

So in short (question)?(result if true):(result is false) , as you can see - it returns the value of the expression so we can simply assign it to a variable just like in the example above.

like image 166
Tushar Gupta - curioustushar Avatar answered Sep 23 '22 01:09

Tushar Gupta - curioustushar