Just prefix lines starting with [
, (
, or ` with a semicolon and you're (almost) golden*
Using the same example as another answer:
var x = { xx : "hello", yy : "world"}
(function () {
console.log("Hello World");
})();
We add a semicolon according to this rule:
var x = { xx : "hello", yy : "world"}
;(function () {
otherwise javascript thinks we're trying to call(
some function, or reference[
some array. This is simpler, easier to follow, and it's visually easier to spot. You also need semicolons in for
loops, but the .forEach
method is a cleaner and easier method. I'd confidently say this one rule covers 99% of the scenarios you need to use a semicolon in javascript/typescript.
Following this method, it's important to associate a newline with terminating a statement.
*This returns the venerable undefined
:
return
7
After return, there's a newline, and the browser inserts a semicolon, terminating the statement like this:
return; // this will return undefined.
7
Do this instead:
return (
7
)
Javascript is actually pretty smart with semicolons, there's an open paren, so no semicolon is inserted until the closing paren is found.
If you have a habit of putting semicolons everywhere and not knowing exactly when they are needed, you could read this for a several page long explanation: http://blog.izs.me/post/2353458699/an-open-letter-to-javascript-leaders-regarding
I admit most people will still just litter semi colons at the end of every line, but if you're new and just learning, this is the better approach.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…