Freddie
Freddie

Reputation: 741

Why is this ternary operator invalid in JS

​var truth = true;
(truth) ? console.log('It is true') : throw new Error('It is not true');​​​​​​​​​​​​​​​

Do ternary operators only accept specific types of objects?

Upvotes: 6

Views: 869

Answers (3)

LWChris
LWChris

Reputation: 4191

It does work, but the problem is the throw statement in your "else" branch.

Use

(truth) ? console.log('It is true') : (function(){throw 'It is not true'}());

Upvotes: 4

SLaks
SLaks

Reputation: 887195

The conditional operator, like all other operators, can only be used with expressions.

throw x; is a statement, not an expression.

Upvotes: 2

antlersoft
antlersoft

Reputation: 14786

javascript distinguishes between statements and expressions. The ternary operator only handles expressions; throw is a statement.

Upvotes: 18

Related Questions