Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
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?
function _throw(msg) { throw new Error(msg); }
truth ? console.log("true") : _throw("It is not true");
javascript distinguishes between statements and expressions. The ternary operator only handles expressions; throw is a statement.
Add a comment
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.
throw x;
Required, but never shown
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.
Explore related questions
See similar questions with these tags.
function _throw(msg) { throw new Error(msg); }then use it in the conditional operator:truth ? console.log("true") : _throw("It is not true");