This time I will bring you some precautions about the use of semicolons in JS. The following is a practical case, let’s take a look.
Semicolons are optional in JavaScript, and the interpreter will automatically complete them under certain conditions.
Code similar to (Example 1):
function myFunction(a) { var num = 10 return a * num }
produces the same result as (Example 2): Code like
function myFunction(a) { var num = 10; return a * num; }
. The interpreter is interpreting A semicolon will be added when .
But the result of the following example is underfined (Example 3):
function myFunction(a) { var num = 10; return a * num; }
The interpreter interprets this code as (Example 4):
function myFunction(a) { var num = 10; return; // 分号结束,返回 undefined a * num; }
The return statement will automatically Shutdown returns an underfined.
It is best not to use semicolons
The splitting rules of statements will lead to some unexpected results. This line of code is written in two lines. According to the meaning of the code It is a complete statement of two lines:
var y=x+f (a+b).toString()
, but the interpreter may misinterpret it as
var y=x+f(a+b).toString();
. It treats f as a function name and interprets two lines of code as one line of code.
In my opinion, it is better to write the code in a clear and standardized way, which will make the code quality and future reading much easier.
The above is the detailed content of Things to note about the use of semicolons in JS. For more information, please follow other related articles on the PHP Chinese website!