Shorthand if ? return : null

4.7k Views Asked by At

I want to achieve this:

 if (full) {
      return
    }
    else{
      // nuthin
    }

But shorter, something like:

full ? return : null;

But that doesn't work..

I could do:

if (full) { return }

But I like the ternary more

I expected something like full ? return to work...

I basically want to break out of the current function when the value is true... Are there any better/working shorthands available?

3

There are 3 best solutions below

0
TrySpace On BEST ANSWER

So this is as short as it gets:

 if full return
0
Bathsheba On

The arguments of a ternary are expressions not statements.

return; is a statement so what you're proposing is not syntatically valid.

Your if statement is about as terse as you can make it: especially if you remove unnecessary braces.

0
Amin NAIRI On

Explainations

If you only want the test if true, you can use the logical AND operator && like so:

index.js:

(function(){
    var full=true;
    full&&alert('Glass is full');
})();

Note that in this example, nothing will happen in case var full=false;.

Source-code

JSFiddle source-code.

Codepen source-code

Pastebin source-files