JavaScript error handling: can I throw an error inside a ternary operator?

You can throw an error like this inside a ternary operator,

function isPositive(a) {
    if(a > 0)
        return "YES";
    throw a == 0 ? Error("Zero Error") : Error("Negative Error");
}

No, it's absolutely not allowed. throw is a statement and it can't be part of an expression.

Unfortunately, I think that's the only way. You can use ifs without the braces:

if(!params.msg) throw new Error("msg is required!");

But there aren't any nice, easy workarounds that I know.


You could do this:

function foo(params) {

    var msg = (params.msg) ? params.msg : (function(){throw "error"}());

    // do stuff if everything inside `params` is defined
}

I wouldn't really recommend it though, it makes for unreadable code.

This would also work (not that it's really much better):

function foo(params) {

    var msg = params.msg || (function(){throw "error"}());

    // do stuff if everything inside `params` is defined
}

Or for a cleaner approach, make a named function.

function _throw(m) { throw m; }
function foo(params) {

    var msg = params.msg || _throw("error");

    // do stuff if everything inside `params` is defined
}