admin管理员组

文章数量:1426450

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?

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?

Share Improve this question edited Jun 2, 2014 at 18:22 TrySpace asked May 27, 2014 at 13:45 TrySpaceTrySpace 2,4708 gold badges37 silver badges65 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 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.

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

So this is as short as it gets:

 if full return

本文标签: javascriptShorthand ifreturnnullStack Overflow