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

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
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)