SoFunction
Updated on 2025-03-03

Some thoughts on JavaScript

As we all know, a sentence of JS code ends with a semicolon and a carriage return will work properly in the browser (at least in my IE7). Don't know if this is a feature of JS language or just a fault-tolerant feature of the interpreter? Since the carriage return character can also be a sign of the end of a sentence, it will be a little more troublesome when compressing JS. To compress all carriage return characters, the program must know where the end of a statement is and add ";" after the end position. This is not easy (maybe there is an easy way I haven't thought of it yet), and in the end, I had to take a compromise method: keep the necessary carriage return characters and remove the carriage return characters before and after the separator such as ";", ",", "+". (How easy would it be if JS ended with ";" like C++ and other languages!)
During the development process, a strange problem was also found. As shown in the following code:
Copy the codeThe code is as follows:

1<body>
2
3<script>
4
5function class1(){};
6
= function ShowMsg()
8{
9 alert("ShowMsg Function!");
10}
11var test = new class1();
();
13</script>
14
15</body>

The above code works fine.
If you remove the "\n" before line 11, the program becomes:
Copy the codeThe code is as follows:

1<body>
2
3<script>
4
5function class1(){};
6
= function ShowMsg()
8{
9 alert("ShowMsg Function!");
10} var test = new class1();
();
12</script>
13
14</body>

Then it will not run correctly because "= function(){...}" cannot mark the end of the statement block. That is to say, the entire "= function(){...}" is just a statement. As mentioned above, a statement must end with a carriage return or ";". This is another major difference from C/C++, etc.
In this regard, it is recommended that when writing JS code in the future, add ";" to end it to avoid unnecessary bugs.
PS: Although JS is powerful, its "defaults" really make me unable to like it.