6
​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?

1
  • You could make a function: function _throw(msg) { throw new Error(msg); } then use it in the conditional operator: truth ? console.log("true") : _throw("It is not true"); Commented Nov 21, 2012 at 22:33

3 Answers 3

18

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

Sign up to request clarification or add additional context in comments.

Comments

4

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'}());

1 Comment

This makes @Freddie code works but does not explain that ternary need to be an expression and not a statement.
2

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

throw x; is a statement, not an expression.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.