Home >Web Front-end >JS Tutorial >Things to note about the use of semicolons in JS

Things to note about the use of semicolons in JS

韦小宝
韦小宝Original
2018-03-19 16:43:111523browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Es6 array extensionNext article:Es6 array extension