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"
...
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With