javascript 's Code structure -Semicolons
1、In mostcases a newline implies a semicolon. But “in most cases” does not mean“always”!
Thereare cases when a newline does not mean a semicolon, now the newline which doesn't add the semicolon automatically , it works~
-----------------------------------------------------------
alert(3 +
1
+ 2);
the result is : 6, yes ,it works~
-----------------------------------------------------------
the reason is : Javascript doesn't insert semicolon in the new line.
It is intuitively obvious that if the line ends with a plus "+", then it is an “incomplete expression”, no semicolon required. And in this case that works as intended.
2、JavaScript does not imply a semicolon before square brackets [...]
-----------------------------------------------------------
alert("There will be an error")
[1, 2].forEach(alert)
the result is :
1. only the first alert is shown
2. we get error info :Uncaught TypeError: Cannot read property '2' of
undefined
-----------------------------------------------------------
the reason is: after the alert ,the semicolon is not auto-inserted , then
the browser sees the code is:
----------------------------------
alert("There will be an error")[1, 2].forEach(alert)
----------------------------------
which is a single statement.
Actually it should be twoseparate statements, not a single one. now it merges one statement, so we get the error.
3、About Function Expression and Function Declaration
Function Expression have asemicolon ; at the end, and Function
Declaration does not. For example:
----------------------------------
function hello() {
alert("hello")
}
let hello = function() { alert("hello") };
----------------------------------
the reason is:
1.There's no need for ; at the end of code blocks and syntax structures
that use them like if { ... }, for { }, function f { } etc.
2.A Function Expression is used inside the statement: let hello = ...;, as a
value. It's not a code block. The semicolon ; is recommended at the end of statements, no matter what is the value.
4、Thereare other situations when the Semicolons (doesn't) exist, if you
know, hope to tell me.