Jpaji Rajnish
Jpaji Rajnish

Reputation: 1501

Can you use a conditional ternary operator by itself? (javascript)

I tried using this construct:

function messageTest(data2, data1, value){
    (!value) ? if (data2 == 0x7F) return true :
                if (data1 == value && data2 == 0x7F) return false;
}

But I get a syntax error. Can you use a ternary operator by itself like this? Also I'm using WSH for this execution.

Upvotes: 0

Views: 731

Answers (3)

Hichem ben chaabene
Hichem ben chaabene

Reputation: 145

You can simplify it, where (data2=== 0x7F) is evaluated as a bool instead of using the IF

function messageTest(data2, data1, value) {
  return (!value ? (data2 === 0x7F) : !((data1 === value) && (data2 === 0x7F)));
}

Upvotes: 0

adeneo
adeneo

Reputation: 318342

You can't have if and return statements inside the ternary, you have to do something like

return value ? !(data1 == value && data2 == 0x7F) : data2 == 0x7F;

note that I flipped it, as doing !value doesn't make sense in this case, and you could also do

return value ? (data1 != value || data2 != 0x7F) : data2 == 0x7F;

Upvotes: 7

Paul S.
Paul S.

Reputation: 66404

Can you use a conditional ternary operator by itself

Yes, any expression can be used by itself

But I get a syntax error

This is because return and if can't be in the middle of an expression

Upvotes: 0

Related Questions