JavaScript single line 'if' statement - best syntax, this alternative?
JavascriptIf StatementJavascript Problem Overview
It's been clearly put, although opinion none the less, that forgoing curly brackets on a single line if
statement is not ideal for maintainability and readability.
But what about this?
if (lemons) { document.write("foo gave me a bar"); }
It's even more compressed, and if expanded, the curly brackets won't be forgotten. Are there any blatant problems, and if not, what are the considerations? I feel like it's still very readable, at least as much as a ternary operator anyway. It seems to me like ternary operators aren't suggested as much due to readability, although I feel like that that conclusion isn't quite as unanimous.
The evil twin in me wants to suggest this, although the syntax obviously isn't meant for it, and is probably just a bad idea.
(syntax) ? document.write("My evil twin emerges"): "";
Javascript Solutions
Solution 1 - Javascript
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.
Solution 2 - Javascript
I use it like this:
(lemons) ? alert("please give me a lemonade") : alert("then give me a beer");
Solution 3 - Javascript
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");
Solution 4 - Javascript
As has already been stated, you can use:
&& style
lemons && document.write("foo gave me a bar");
or
bracket-less style
if (lemons) document.write("foo gave me a bar");
short-circuit return
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'
Solution 5 - Javascript
This one line is much cleaner.
if(dog) alert('bark bark');
I prefer this. hope it helps someone
Solution 6 - Javascript
can use this,
lemons ? alert("please give me a lemonade") : alert("then give me a beer");
explanation: if lemons
is true then alert("please give me a lemonade")
, if not, alert("then give me a beer")
Solution 7 - Javascript
As a lot of people have said, if you're looking for an actual 1 line if then:
if (Boolean_expression) do.something();
is preferred. However, if you're looking to do an if/else then ternary is your friend (and also super cool):
(Boolean_expression) ? do.somethingForTrue() : do.somethingForFalse();
ALSO:
var something = (Boolean_expression) ? trueValueHardware : falseATRON;
However, I saw one very cool example. Shouts to @Peter-Oslson for &&
(Boolean_expression) && do.something();
Lastly, it's not an if statement but executing things in a loop with either a map/reduce or Promise.resolve() is fun too. Shouts to @brunettdan
Solution 8 - Javascript
// Another simple example
var a = 11;
a == 10 ? alert("true") : alert("false");
Solution 9 - Javascript
I've seen many answers with many votes advocating using the ternary operator. The ternary is great if a) you do have an alternative option and b) you are returning a fairly simple value from a simple condition. But...
The original question didn't have an alternative, and the ternary operator with only a single (real) branch forces you to return a confected answer.
lemons ? "foo gave me a bar" : "who knows what you'll get back"
I think the most common variation is lemons ? 'foo...' : ''
, and, as you'll know from reading the myriad of articles for any language on true, false, truthy, falsey, null, nil, blank, empty (with our without ?) , you are entering a minefield (albeit a well documented minefield.)
As soon as any part of the ternary gets complicated you are better off with a more explicit form of conditional.
A long way to say that I am voting for if (lemons) "foo"
.
Solution 10 - Javascript
(i === 0 ? "true" : "false")
Solution 11 - Javascript
It can also be done using a single line when using if
blocks like this:
if (blah)
doThis();
It also works with while
loops.
Solution 12 - Javascript
Example in arrow functions:
let somethingTrue = true
[1,2,3,4,5].map(i=>somethingTrue && i*2)
In promises:
Promise.resolve()
.then(_=>checkTrueFalse && asyncFunc())
.then(_=>{ .. })
Otherwise:
if(somethingTrue) thenDo()
If it's just a simple conditional, I prefer using if(value) whenever possible because the word if in the beginning of the statement says more about what's happening than paranthesis and questionmarks.
Solution 13 - Javascript
**Old Method:**
if(x){
add(x);
}
New Method:
x && add(x);
Even assign operation also we can do with round brackets
exp.includes('regexp_replace') && (exp = exp.replace(/,/g, '@&'));