javascript 's Code structure -Semicolons
1、In most cases a newline implies a semicolon. But “in most cases” does not mean “always”!There are cases when a newline does not mean a semicolon, now the newline which doesn't add thesemicolon automatically , it works~-----------------------------------------------------------alert(3 +1+ 2);the result is : 6, yes ,it works~-----------------------------------------------------------the reason is : Javascript doesn't insertsemicolon 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 firstalertis shown2. we get error info :Uncaught TypeError: Cannot read property '2' ofundefined-----------------------------------------------------------the reason is: after the alert ,the semicolon is not auto-inserted , thenthe browser sees the code is:----------------------------------alert("There will be an error")[1, 2].forEach(alert)----------------------------------which is a single statement.Actually it should be two separate statements, not a single one. now it merges one statement, so we get the error.
3、About Function Expression and Function DeclarationFunction Expressi泠贾高框on have a semicolon;at the end, and FunctionDeclaration 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 structuresthat use them likeif { ... },for { },function f { }etc.2.A Function Expression is used inside the statement:let hello = ...;, as avalue. It's not a code block. The semicolon;is recommended at the end of statements, no matter what is the value.
4、There are other situations when theSemicolons (doesn't) exist, if youknow, hope to tell me.