0

I'm using:

MyTestFunction() && ExecuteMe();

for quick and easy conditional execution. I'd like to improve the code readability more in some places by creating:

  1. Single line guard statments I.E:

    MyTestFunction() && return; 
    //prevent execution of function early, but this isn't possible
    
  2. Single line variable setters:

    MyTestFunction() && myVar = 5;
    

    (I realise I can do myVar = MyTestFunction() || 5; but that's not what I want)

Anyone see a nice way around this?

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
williamsandonz
  • 15,864
  • 23
  • 100
  • 186
  • 2
    Why not just write more readable code using an `if` statement and be done with it? Brevity is not the #1 goal of writing code. When it gets in the way of all the other more important goals like correctness and readability, brevity should be sacrificed. – jfriend00 Feb 28 '12 at 02:39
  • Yes I agree, I love the single-line assignment that imm has come up with, but for single line guard statements, I think for lack of a better solution, I'll be using: if(!myTest()) { return; } – williamsandonz Feb 28 '12 at 02:48

4 Answers4

3

This works for me:

var num;
TestFunc() && (num = 5);
imm
  • 5,837
  • 1
  • 26
  • 32
1

While I understand the programmers innate desire to do more things in less lines of code I think this violates some good programming principles about clarity in your code. Terse code saves space, but makes maintenance harder for the next programmer who looks at your code (and you should always assume there will be a "next programmer").

davidethell
  • 11,708
  • 6
  • 43
  • 63
1
MyTestFunction() && (myVar = 5);         // note the parens

// has the same effect as

if (MyTestFunction()) myVar = 5;

But I think the latter is much more readable and therefore easier to maintain.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
0

I believe you are wanting to use a ternary statement

good thread here: Operator precedence with Javascript Ternary operator

Community
  • 1
  • 1
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • Can't do this with a ternary, !myTest() ? return; : null; is invalid syntax. – williamsandonz Feb 28 '12 at 02:44
  • How can you rewrite `MyTestFunction() && myVar = 5;` with the ternary operator, given that the original expression only has two parts? You could say `MyTestFunction() ? myVar = 5 : void 0;` but that's not very useful. – nnnnnn Feb 28 '12 at 02:47