user3144851
user3144851

Reputation: 39

If true … else Shorthand

I know that the normal use case for this if statement is e.g.

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

I use jhint in my editor and when i try something like

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

jshint throws (W030) "Expected an assignment or function call and instead saw an expression"

So far the code always worked fine but maybe i was just lucky.

So my question is, why should i not use this pattern and what would be an alternative? Because writing

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

for such short instructions really give me the creeps.

thank you.

Upvotes: 3

Views: 635

Answers (5)

Salman Arshad
Salman Arshad

Reputation: 272066

It is possible to wrap the ternary operator inside the void operator like this:

void(cond ? expr1 : expr2);

This achieves the desired result and passes JSHint. See JSFiddle and click JSHint button.

However, I recommend the following syntax:

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

Because it is more readable. Just because JavaScript lets you do strange things does not mean that you should.

Upvotes: 5

Trudbert
Trudbert

Reputation: 3188

What it complains about is you misappropriating the conditional operator. It is an operator not a control structure. So it lives in the category of such things things as +,-,*,/. That means you expect the first operand to be a boolean and the second and third to yield a return value.

The whole thing is meant to be short for

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

It wants to return a value (which it can't in your case) and it expects you to use that value (which you don't). So the tenary if is not the thing to use for your case and as a result makes it far less readable.

Upvotes: 3

YMMD
YMMD

Reputation: 3780

If you really want to use the ternary operater for this kind of operation in a clean way, then 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 anyway you may prefer a boring if statement.

Upvotes: 1

KooiInc
KooiInc

Reputation: 122908

You can circumvent the jshint message using:

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

Upvotes: 1

Pieter21
Pieter21

Reputation: 1845

You are using side effects in expressions to execute logic.

Indeed not very friendly code. It will work.

Just rewrite to distinct logic from expressions.

Upvotes: 1

Related Questions