JavaScript single line 'if' statement - best syntax, this alternative?

David Hobs picture David Hobs · Jan 14, 2012 · Viewed 438k times · Source

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"): "";

Answer

Peter Olson picture Peter Olson · Jan 14, 2012

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.