JavaScript single line ‘if’ statement – best syntax, this alternative?

JavaScript single line ‘if’ statement – best syntax, this alternative?

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”): “”;

Solutions/Answers:

Solution 1:

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:

Related:  How to force remounting on React components?
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:

I use it like this:

(lemons) ? alert("please give me a lemonade") : alert("then give me a beer");

Solution 3:

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:

// Another simple example

 var a = 11;
 a == 10 ? alert("true") : alert("false");

Solution 5:

This one line is much cleaner.

if(dog) alert('bark bark');

I prefer this. hope it helps someone

Solution 6:

can use this,

lemons ? alert("please give me a lemonade") : alert("then give me a beer");

explanation :
if lemons exist then give me an alert("please give me a lemonade") else alert("then give me a beer")