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?
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?
Share Improve this question asked Nov 21, 2012 at 22:27 FreddieFreddie 7412 gold badges10 silver badges23 bronze badges 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");
– I Hate Lazy Commented Nov 21, 2012 at 22:33
3 Answers
Reset to default 18javascript distinguishes between statements and expressions. The ternary operator only handles expressions; throw is a statement.
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'}());
The conditional operator, like all other operators, can only be used with expressions.
throw x;
is a statement, not an expression.