javascript 's Code structure -Semicolons

 时间:2026-02-16 16:08:37

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.

  • What is JavaScript?
  • Myeclipse导入工程后出错:Missing semicolon
  • vs code简单设置pylint
  • Visual Studio Code Mac怎么运行JavaScript
  • Javascript原型
  • 热门搜索
    外出旅游必备物品清单 江苏旅游政务网 枣庄旅游景点大全 深圳的旅游景点 兴城旅游攻略 青藏线旅游攻略 福建 旅游 那曲旅游 峨嵋山旅游 迪拜旅游注意事项