Just as you can convert the following:
var t;
if(foo == "bar") {
t = "a";
} else {
t = "b";
}
into:
t = foo == "bar" ? "a" : "b";
, I was wondering if there is a shorthand / oneline way to convert this:
var t;
try {
t = someFunc();
} catch(e) {
t = somethingElse;
}
Is there a method of doing this in a shorthand way, preferably an oneliner? I could, of course, just remove the newlines, but I rather mean something like the ? :
thing for if
.
Thanks.
You could use the following function and then use that to oneline your try/catch. It's use would be limited and makes the code harder to maintain so i'll never use it.
var v = tc(MyTryFunc, MyCatchFunc);
tc(function() { alert('try'); }, function(e) { alert('catch'); });
/// try/catch
function tc(tryFunc, catchFunc) {
var val;
try {
val = tryFunc();
}
catch (e) {
val = catchFunc(e);
}
return val;
}