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

This question is related to javascript if-statement

The answer is


It can also be done using a single line with while loops and if like this:

if (blah)
    doThis();

It also works with while loops.


I use it like this:

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

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


**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, '@&'));

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".


// Another simple example

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

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

(i === 0 ? "true" : "false")

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


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.


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'


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.


This one line is much cleaner.

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

I prefer this. hope it helps someone