309

Can I write the if else shorthand without the else?

var x=1;

x==2 ? dosomething() : doNothingButContinueCode();   

I've noticed putting null for the else works (but I have no idea why or if that's a good idea).

Edit: Some of you seem bemused why I'd bother trying this. Rest assured it's purely out of curiosity. I like messing around with JavaScript.

20
  • I think there's a var | var syntax. Careful as it's potentially difficult to "see", especially (IMO) ternaries being problematic. Use sparingly. Jun 17, 2012 at 6:03
  • @JaredFarrish Isn't the whole point of ternaries that they're easier to "see" than using if statements? Also what is that syntax you're talking about, it looks interesting .
    – user377628
    Jun 17, 2012 at 6:06
  • 1
    No, I don't think they're easier to at all in all cases. The "whole point" in my mind is to either put it all on one line ("my codes shorter than yours") or for specific, literal cases with simplistic outcomes. Stacking ternaries is particularly pernicious and should be avoided at all cost. :) Jun 17, 2012 at 6:08
  • 2
    @Hassan - I've seen something like foo = bar | cat;, where if the first is false? null?, it "falls through" to the second. I've only seen it, though, and don't use it. Jun 17, 2012 at 6:09
  • 4
    @JaredFarrish: That's a || b or a && b, otherwise b will always be evaluated.
    – kennytm
    Jun 17, 2012 at 6:11

8 Answers 8

755

What you have is a fairly unusual use of the ternary operator. Usually it is used as an expression, not a statement, inside of some other operation, e.g.:

var y = (x == 2 ? "yes" : "no");

So, for readability (because what you are doing is unusual), and because it avoids the "else" that you don't want, I would suggest:

if (x==2) doSomething();
3
  • In here we can add finishing line inserted as a full command (as my example use jquery fade in and fade out function) x == 2 ? $(element).fadeIn() :$(element).fadeIn() ; It not mandatory to have a return variable( like var y in first code). Jul 21, 2014 at 17:15
  • 1
    you must use triple "=" signs for the logic to be perfect. as in var y = (x === 2 ? "yes" : "no");
    – fino
    Dec 24, 2014 at 21:11
  • Triple equal operator is only necessary when there may be type coercion between left and right arguments, and only if you don't actually intend to use type coercion. Sep 18, 2021 at 12:50
296

This is also an option:

x==2 && dosomething();

dosomething() will only be called if x==2 is evaluated to true. This is called Short-circuiting.

It is not commonly used in cases like this and you really shouldn't write code like this. I encourage this simpler approach:

if(x==2) dosomething();

You should write readable code at all times; if you are worried about file size, just create a minified version of it with help of one of the many JS compressors. (e.g Google's Closure Compiler)

9
  • 10
    Oh, short-circuiting, right. Code readability is under appreciated I think in most intermediate developers and some "seasoned professionals". Jun 17, 2012 at 6:35
  • 2
    Technically you don't need the braces: if (1 - 1 === 0) $('.woot').text('Woot!'); I use that form all the time with PHP, and now that I'm adopting Coffeescript, I use it in my Javascript as well. Sep 14, 2012 at 0:13
  • 5
    I personally believe if it is a small if with one outcome if true.. its quicker and easier to write x == 2 && dosomething(); Feb 18, 2014 at 15:24
  • 9
    if x==2 && doSomething() || doSomethingElse()
    – Agustín
    Mar 31, 2015 at 14:54
  • 2
    I wish JavaScript included this Ruby-like syntax: doSomething() if x === 2. I don't miss Ruby, but I do miss that. Jul 26, 2018 at 15:56
65

Another option:

x === 2 ? doSomething() : void 0;
1
  • 3
    If someone don't know why use void 0 i suggest read this link
    – Carlinhos
    Jul 5, 2017 at 19:50
23

If you're not doing the else, why not do:

if (x==2) doSomething();
1
  • 5
    you can do it even if you do the else
    – nmirceac
    Jan 24, 2014 at 20:38
17

Using null is fine for one of the branches of a ternary expression. And a ternary expression is fine as a statement in Javascript.

As a matter of style, though, if you have in mind invoking a procedure, it's clearer to write this using if..else:

if (x==2) doSomething;
else doSomethingElse

or, in your case,

if (x==2) doSomething;
7

A small addition to this old thread..

If you're evaluating an expression inside a for/while loop with a ternary operator and want to continue or break as a result - you're going to have a problem because both continue & break aren't expressions; they're statements without any value.

This will produce Uncaught SyntaxError: Unexpected token continue

for (const item of myArray) {
    item.value ? break : continue;
}

If you really want a one-liner that returns a statement, you can use this instead:

for (const item of myArray) {
    if (item.value) break; else continue;
}
  • P.S - This code might raise some eyebrows. Just saying.. :)
4

Technically, putting null or 0, or just some random value there works (since you are not using the return value). However, why are you using this construct instead of the if construct? It is less obvious what you are trying to do when you write code this way, as you may confuse people with the no-op (null in your case).

3

Probably shortest (based on OR operator and its precedence)

x-2||dosomething()

let x=1, y=2;
let dosomething = console.log; 

x-2||dosomething('x do something');
y-2||dosomething('y do something');

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.