How can I use an inline if
statement in JavaScript? Is there an inline else
statement too?
Something like this:
var a = 2;
var b = 3;
if(a < b) {
// do something
}
How can I use an inline if
statement in JavaScript? Is there an inline else
statement too?
Something like this:
var a = 2;
var b = 3;
if(a < b) {
// do something
}
FYI, you can compose conditional operators
If your logic is sufficiently complex, then you might consider using an IIFE
Of course, if you plan to use this logic more than once, then you aught to encapsulate it in a function to keep things nice and DRY.
Isn't the question essentially: can I write the following?
the answer is, yes, the above will translate.
however, be wary of doing the following
be sure to wrap ambiguous code in braces as the above will throw an exception (and similar permutations will produce undesired behaviour.)
For writing
if
statement inline, the code inside of it should only be one statement:You can also approximate an if/else using only Logical Operators.
The above is roughly the same as saying:
And of course, roughly the same as:
I say roughly because there is one difference with this approach, in that you have to know that the value of
b
will evaluate as true, otherwise you will always getc
. Bascially you have to realise that the part that would appearif () { here }
is now part of the condition that you placeif ( here ) { }
.The above is possible due to JavaScripts behaviour of passing / returning one of the original values that formed the logical expression, which one depends on the type of operator. Certain other languages, like PHP, carry on the actual result of the operation i.e. true or false, meaning the result is always true or false; e.g:
One main benefit, compared with a normal if statement, is that the first two methods can operate on the righthand-side of an argument i.e. as part of an assignment.
The only way to achieve this with a standard if statement would be to duplicate the assigment:
You may ask why use just Logical Operators instead of the Ternary Operator, for simple cases you probably wouldn't, unless you wanted to make sure
a
andb
were both true. You can also achieve more streamlined complex conditions with the Logical operators, which can get quite messy using nested ternary operations... then again if you want your code to be easily readable, neither are really that intuative.To add to this you can also use inline if condition with && and || operators. Like this
You don't necessarily need jQuery. JavaScript alone will do this.
The
c
variable will beminor
if the value istrue
, andmajor
if the value isfalse
.This is known as a Conditional (ternary) Operator.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Conditional_Operator