In Javascript (or for the most part, ECMAscript in general), which is the most appropriate way to write this?
try { ajax.abort() } catch(e) { console.error (e) }
try { ajax.abort(); } catch(e) { console.error (e); }
It seems like semi-colons are unneeded for this situation but at the same time I normally write this on 5 lines instead of one in which case I used semicolons for their standard programmatic purpose (eol).
Both work, and I'm sure both will validate, so which is semantically correct?
Here's an inline try-catch for expressions. You can compute a value in one go, but still catch exceptions and fall back to a default value when evaluation fails - similar in spirit to the ternary ?: operator:
function trycatch(func, fail) {
try { return func() }
catch(e) { return fail }
}
The expression must be wrapped up in a function, so it gets executed inside trycatch() not outside of it. Example use:
let value = trycatch(() => JSON.parse("parsing fails on this input"), null)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With