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.
In JavaScript we have the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.
Javascript offers a ternary operator which acts like a one-line if / else statement with a single condition. It works really well for conditionally assigning a value to a variable.
I've seen the short-circuiting behaviour of the &&
operator used to achieve this, although people who are not accustomed to this may find it hard to read or even call it an anti-pattern:
lemons && document.write("foo gave me a bar");
Personally, I'll often use single-line if
without brackets, like this:
if (lemons) document.write("foo gave me a bar");
If I need to add more statements in, I'll put the statements on the next line and add brackets. Since my IDE does automatic indentation, the maintainability objections to this practice are moot.
I use it like this:
(lemons) ? alert("please give me a lemonade") : alert("then give me a beer");
You could use this format, which is commonly used in PHP:
(lemon) ? document.write("foo gave me a bar") : document.write("if condition is FALSE");
As has already been stated, you can use:
lemons && document.write("foo gave me a bar");
or
if (lemons) document.write("foo gave me a bar");
If, however, you wish to use the one line if
statement to short-circuit a function though, you'd need to go with the bracket-less version like so:
if (lemons) return "foo gave me a bar";
as
lemons && return "foo gave me a bar"; // does not work!
will give you a SyntaxError: Unexpected keyword 'return'
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