3

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?

TrySpace
  • 2,233
  • 8
  • 35
  • 62

3 Answers3

5

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

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

Amin NAIRI
  • 2,292
  • 21
  • 20
-1

So this is as short as it gets:

 if full return
TrySpace
  • 2,233
  • 8
  • 35
  • 62