If true ... else Shorthand

I know there is a common use case for this if statement, for example

var string = boolean ? "this" : "that";

      

I am using jhint in my editor and when I try something like

boolean ? array.push("this") : array.slice("that",1);

      

jshint throws (W030) "A function assignment or call was expected and instead an expression was seen."

So far, the code has always worked fine, but maybe I was just lucky.

So my question is, why shouldn't I use this pattern and what would be the alternative? Since the record

if(boolean){
    array.push("this");
} else {
    array.splice("that",1);
}

      

for such short instructions really give me creeps.

thank.

+3


source to share


5 answers


It is possible to bind a 3D operator internally like this: void operator

void(cond ? expr1 : expr2);

      

This provides the desired output and passes the JSHint. See the JSFiddle and click the JSHint button.



However, I recommend the following syntax:

if (cond) {
    expr1;
} else {
    expr2;
}

      

Because it is more readable. Just because JavaScript lets you do weird things doesn't mean you should.

+5


source


What he's complaining about is the assignment of a conditional operator. It is an operator, not a control structure. Therefore, he lives in the category of things like +,-,*,/

. This means that you expect the first operand to be a boolean and the second and third to be a return value.

All this should be short for



  if (boolean) {
   string ="this" ;
  } else {
   string ="that";
  }

      

It wants to return a value (which may not be in your case), and it expects you to use that value (which you don't). So tenary if that's not what you need to use for your case, and makes it less readable as a result.

+3


source


You use side effects in expressions to do your logic.

Really not very friendly code. It will work.

Just rewrite to different logic from expressions.

+1


source


You can get around the jshint message using:

void(boolean ? array.push("this") : array.slice("that",1));

      

+1


source


If you really want to use the ternary operand for this kind of operation in a clean way, you can do it like this:

array[cond ? 'push' : 'slice'](cond ? "this" : "that", cond ? 1 : undefined);

      

or

array[cond ? 'push' : 'slice'].apply(null, cond ? ["this"] : ["that", 1]);

      

But you might prefer the sparkling if statement anyway.

+1


source







All Articles