Omitting the second expression when using the if-else shorthand

Omitting the second expression when using the if-else shorthand

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.

Solutions/Answers:

Solution 1:

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)

Solution 2:

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

Solution 3:

Another option:

x === 2 ? doSomething() : void 0;

Solution 4:

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

if (x==2) doSomething();

Solution 5:

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;

Solution 6:

A tiny addition to this very, very old thread..

Let’s say your’e inside a for loop and need to evaluate a variable for a truthy/falsy value with a ternary operator, while in case it’s falsy you want to continue – you gonna have a problem because your’e not returning an expression ,you return instead a statement without any value.

This will produce Uncaught SyntaxError: Unexpected token continue

 for (var i = 0; i < myArray.length; i++) {
      myArray[i].value ? alert('yay') : continue;
 }

So, if you do want to return a statement and still use one line for your code, while it may seem kinda weird at first glance and may not follow strict language usage, you can do this instead:

  for (var i = 0; i < myArray.length; i++) {
      if (myArray[i].value) alert('yay') ; else continue;
  }
  • P.S – This code may be hard to read or understand so it will not always be the best option to use. Just saying.. 🙂