313

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"): "";
BobRodes
  • 5,990
  • 2
  • 24
  • 26
David Hobs
  • 4,351
  • 2
  • 21
  • 22
  • 4
    Would be nice if JavaScript supported end of phrase conditionals: `document.write("My evil twin emerges") if lemons` – Beau Smith Feb 10 '13 at 02:57
  • 9
    I think you might be thinking about the short if, else statement. (`variable = (condition) ? true-value : false-value;`.) Good luck. – Progo Jan 11 '14 at 04:28

13 Answers13

457

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.

revelt
  • 2,312
  • 1
  • 25
  • 37
Peter Olson
  • 139,199
  • 49
  • 202
  • 242
  • 1
    you should know what you are expecting, since empty string and 0 are falsy values, it will fail the execute the second statement – Orlando Jul 31 '13 at 17:45
  • 1
    Of course, you can just as well put a more explicit boolean statement in there – acjay Nov 01 '13 at 15:23
  • @acjohnson55 What do you mean? – Peter Olson Nov 01 '13 at 20:17
  • I meant that in response to Orlando. Should have used my @ sign. Basically just saying that your approach is still valid if you don't want to rely on truthyness/falseyness – acjay Nov 01 '13 at 21:45
  • The second statement will fail linting and is not recommended – danwellman Mar 08 '14 at 09:02
  • @danwellman That depends on what linter you use and how you configure it. – Peter Olson Mar 08 '14 at 13:05
  • you can configure linters not to warn against eval, but it doesn't mean it's a good idea to use it ;) – danwellman Mar 08 '14 at 14:46
  • 7
    @PeterOlson why are the maintainability objections moot? What if any other developer happens to not use your IDE with its configuration. – agconti Jul 10 '14 at 16:35
  • A small aside: the short circuiting behaviour of some logical operators can, IMO, be an excellent way to control code execution i.e. you can set default values if a user hasn't defined one in their environment (say, with `const envVar = process.env.SOME_VARIABLE || defaultValue`) - but in the case of checking definition, I don't see it used as often. Another advantage of using if is being able to negate with `if !(lemons) yourCode` – GrayedFox Aug 15 '18 at 14:49
  • you can't use the `&&` style with short circuiting functions (and returning early), you can do that with the bracket-less if one-liner. – Marc Oct 26 '18 at 18:36
200

I use it like this:

(lemons) ? alert("please give me a lemonade") : alert("then give me a beer");
whirish
  • 450
  • 4
  • 18
asael2
  • 2,147
  • 1
  • 12
  • 11
54

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");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Macro
  • 549
  • 4
  • 2
  • 15
    You don't need brackets on the `lemon`. – leymannx Nov 16 '15 at 09:16
  • 9
    Can be best practice to include () around a conditional statement - removes any confusion as to order of operations etc. for other developers. I typically err towards specifying it except when there's no way for someone decently qualified to get confused. – djvs Apr 18 '17 at 04:11
  • 4
    `document.write(lemon ? "foo gave me a bar" : "if condition is FALSE");` :) – Joseph Goh Dec 05 '17 at 12:33
  • 1
    I like the brackets as to me they imply a boolean coercion. – Daniel Sokolowski Apr 11 '18 at 05:01
52

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'

Marc
  • 4,820
  • 3
  • 38
  • 36
  • In single line short-circuits, we can omit 'return' and it should work as expected. ``` lemons && "foo gave me a bar"; // works! ``` – siwalikm Apr 26 '19 at 12:08
  • @siwalikm could you explain? This is for the case where you don't want to return `lemons` (if it's falsey) -- you only want to return "foo gave me bar" when `lemons` is truthy. – Marc Apr 26 '19 at 15:44
  • if (lemons) return "foo gave me a bar"; this is wrong. It will give you "Uncaught SyntaxError: Illegal return statement" – Fenec May 05 '20 at 10:19
  • @Fenec would you share the browser and version that causes you this error? This worked for me almost 2 years ago and continues to work for me. – Marc May 05 '20 at 12:29
28

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

Community
  • 1
  • 1
Mohideen bin Mohammed
  • 18,813
  • 10
  • 112
  • 118
25

This one line is much cleaner.

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

I prefer this. hope it helps someone

shakee93
  • 4,976
  • 2
  • 28
  • 32
24

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

Kemacal
  • 391
  • 3
  • 5
17

// Another simple example

 var a = 11;
 a == 10 ? alert("true") : alert("false");
user3413838
  • 310
  • 4
  • 14
12
(i === 0 ? "true" : "false")
Abdulmajeed
  • 552
  • 7
  • 8
9

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

Anita Graham
  • 456
  • 1
  • 5
  • 13
6

It can also be done using a single line when using if blocks like this:

if (blah)
    doThis();

It also works with while loops.

sergiol
  • 4,122
  • 4
  • 47
  • 81
Noitidart
  • 35,443
  • 37
  • 154
  • 323
2

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.

brunettdan
  • 997
  • 9
  • 7
1
**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, '@&'));
Sajith Mantharath
  • 2,297
  • 2
  • 17
  • 19
  • "Even assign operation also we can do with round brackets". This is very interesting, I didn't know that it was possible to do assign operations inside these single-line operations. – Renato Probst May 15 '20 at 17:47