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?
They're semantically identical, and they're both syntactically correct, because of Automatic Semicolon Insertion.
This part is opinion:
I recommend always writing the necessary semicolons explicitly and never relying on ASI. But even if you do that, ASI can bite you. The classic example is:
function foo() {
return
"testing";
}
If you call foo
, the return value will be undefined
, not "testing"
, because ASI kicks in and adds a ;
after the return
. Ouch.