Use a semicolon at the end of lines in javascript?

54

I've read some web comments about whether or not to use ; at the end of the lines when writing JavaScript. Some say yes, others say they have no need, but none can explain the reasons for the divergences.

Example:

var ola = "Olá"; // com ponto e vírgula
var mundo = "Mundo"  // sem ponto e vírgula

The interesting thing is that even forgetting ; in my code sometimes, it keeps running without problems and without triggering errors. So, is it okay to use the famous semicolon?

    
asked by Kazzkiq 31.01.2014 в 01:18
source

6 answers

41

Always use ; and this is because:

JavaScript is a language that makes statements to the browser. The character used to separate these statements is ; and it should always be used.

The code can work without the semicolon after a statement, but for this there must be an end-of-line or a correct syntax.

Thank you to @Gabriel Gartz for alerting us to the fact that any logical operator, mathematical or scope delimitation allows to generate code execution equally.

The biggest problem comes from the fact that we all want to optimize the files downloaded to the browser, such as .js and .css files for which we apply compression (remove line breaks, comments, spaces and tabulations). In these cases, if there is no correct separation of declarations to the browser, they will be interconnected and syntax errors will appear.

Let's look at examples:

  • Example 01 (click to open JSFIddle)

    Make an alert without the ; :

    alert("olá")
    

    It runs all as expected, we received an alert.

  • Example 02 (click to open JSFIddle)

    Make two alerts without the claims separator, but each alert on your line separated by "end-of-line":

    ( r , n or rn depending on the operating system where the file was created)

    alert("olá")
    alert("olá novamente")
    

    It runs all as expected, we received two alerts.

  • Example 03 (click to open JSFIddle)

    Make two separate alerts with the ; :

    alert("olá"); alert("olá novamente")
    

    It runs all as expected, we received two alerts.

  • Example 04 (click to open JSFIddle)

    Make two alerts without separating statements ; and with compressed code:

    alert("olá")alert("olá novamente")
    

    Nothing happens and we get a script error on the page:

      

    SyntaxError: missing; before statement

         

    alert ("hello") alert ("hello again")

  • Example 05 (click to open JSFIddle)

    Based on the call made by @Gabriel Gartz, you can verify that if the syntax is correct, the code runs without errors, even if the statements are separated by something other than ; :

    alert('foo')&alert('bar')|alert('zaz')
    

    It will generate three alerts as expected.

Automatic insertion of the semicolon ( ; )

There are some declarations that automatically receive an insertion of ; :

┌────────────┬────────────────────────────────────┐
│ DECLARAÇÃO │ EXEMPLO DA DECLARAÇÃO              │
├────────────┼────────────────────────────────────┤
│ empty      │ ;                                  │
├────────────┼────────────────────────────────────┤
│ variable   │ var a = 1;                         │
├────────────┼────────────────────────────────────┤
│ expression │ greeting = "Hello " + name;        │
├────────────┼────────────────────────────────────┤
│ do-while   │ do qualquerCoisa while (condição); │
├────────────┼────────────────────────────────────┤
│ continue   │ continue;                          │
├────────────┼────────────────────────────────────┤
│ break      │ break;                             │
├────────────┼────────────────────────────────────┤
│ return     │ return;                            │
├────────────┼────────────────────────────────────┤
│ throw      │ throw "Error2";                    │
└────────────┴────────────────────────────────────┘

These are declarations that must be terminated with the declaration argument ; , which is why they are automatically inserted if it is not found.

What are the rules for this to happen:

Code reading is performed from left to right. If an offensive symbol symbol is found that is not allowed in any grammar production, a semicolon is automatically inserted if one of the following conditions is true:

  • The offending symbol is separated from the previous symbol in at least one "end-of-line";
  • The token is } .

Notes:

Automatic insertion of statement separators is an extended topic subject to many rules, but explains why we can get the code to work without using the declarations tab when we have a "end-of-line" or a valid syntax.

In case of files already compressed to suppress unnecessary characters to the maximum, it is almost impossible to insert the declarations separator automatically, as one of the above conditions is no longer present.

Documentation: 7.9 Automatic Semicolon Insertion (English)

    
answered by 31.01.2014 / 01:37
source
8

Point and comma in javascript is optional as an instruction separator, however one should be very careful.

A case like:

a = b + c
(d + e).print()

It will be evaluated as: a = b + c(d + e).print(); (as seen here )

In the case of for , however, the use of semicolons is mandatory within its syntax:

for (var i=0; i < 10; i++) 

If there is no body of instructions to be executed a semicolon should be added, otherwise a block like:

 for (var i = 0; i < 5; alert(i), i++)
 document.write("oi")

It will be interpreted as:

 for (var i = 0; i < 5; alert(i), i++)
 {
  document.write("oi")
 }

So to avoid this, the semicolon should be added and the code looks like this:

for (var i = 0; i < 5; alert(i), i++);
document.write("oi")

In the case of more than one statement on the same line, the use of semicolons is mandatory.

var i; i = 42
    
answered by 31.01.2014 в 01:46
8

I recommend reading this article from Caio Gondim, because the non-use can cause several situations and it is good to know how to understand each one.

link

In short [...] ; serves as a declaration delimiter. But because of ASI, \n will also function as a statement delimiter, except in the following cases:

1 - The statement has a parentheses, literal array, or literal object that is not closed, or ends in any other way which is not a valid way to end a statement. 2 - The entire line is a -- or ++ (in this case, it will increment / decrement the next token)
3 - Is for() , while() , do , if() or else and there is no {
4 - The next line starts with [ , ( , + , - , * , / , , , . , or any other binary operator that can only be found between two tokens in a single expression. [...]

That is, in the four situations mentioned above ASI will not be triggered, in other situations ASI will normally interpret \n as a delimiter.

    
answered by 31.01.2014 в 01:36
5

Zuul's answer is correct. I'll just leave a specific case here because no one has so far commented on:

This:

function foo () {
    return
    {
        name: "bar"
    }
}

It's equivalent to this:

function foo () {
    return;
    {
        name: "bar"
    };
}

Come on, run both forms in the console of your browser;)

And if you do not pay attention to this fact, you can make mistakes more often.

Using a semicolon is not required, but it is a good practice because it makes it clearer where one expression ends and another begins.

    
answered by 28.10.2014 в 18:23
4

The semicolon in Javascript is used to force the interpretation of the syntax in a line, delimiting this execution to the excerpt that precedes the semicolon.

You are not required to use the semicolon to delimit an execution; there are other ways, such as logical operators or scope definitions, but it is a good practice to use semicolons.

The line break also delimits the syntax that will be executed.

Example:

alert('foo'); alert('bar');

You will first run the function that creates an alert with foo and then with alert displaying bar

The same result can be obtained with the & or |

alert('foo') & alert('bar') | alert('zaz')

Or even just breaking the line.

But if you write everything together, without any operator, JSC will not know how to delimit the execution of your syntax and will expose an error with an identifier not found.

Another curious way to delimit is to create a scope using the keys, for example:

{alert('foo')}alert('bar')

Mathematical Operators:

alert('foo')+alert('bar')-alert('zaz')

Of course all these alternative ways are just a curiosity of JSC, it is recommended that you always use the semicolon to delimit the interpretation of their syntax.

    
answered by 31.01.2014 в 02:01
3

First of all, I would like to point out that the semicolon sometimes separates statements (when I refer to 'statements' I mean declarations, declarations of expression and other instructions that may appear in common bodies), but in other Sometimes it becomes a statement that does nothing. For example, the ECMAScript3 tag requires a statement on the front (and the appropriate tag declaration name is LabelledStatement ):

/* Funciona. */
StatementEtiquetado: ;

/* Aqui, esse ponto e vírgula apenas delimita
 * os LabelledStatements abaixo. A declaração de expressão 2 se torna
 * o LabelledStatement, enquanto o ponto e vírgula é desnecessário.  */
StatementEtiquetado: 2;

/* Não funciona porque não tem statement, :/ . */
StatementEtiquetado:

The semi-colon (semicolon) can appear in any unused space in a body of statements, even at the top ( see in Esprima ):

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
( \u{41} => void 0)'';
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

for (;;)
/* Esse semicolon é o corpo desse loop, embora. */
    ;

Strange to do this in a language like ActionScript 3, and still work!

In both ECMAScript and Lua I usually use semicolon because it is imperative. Without using semicolon, sometimes it is also possible to cause problems with calls:

{
    let expressão = _ => void 0;

    expressão()
    (_ => void 0) ''
}

Or you can use commas instead of semicolons, which generate a sequence of expressions:

chamada(),
(_ => void 0)()

But apparently, without the use of semicolon, it can only affect calls that use expressions around parentheses. Remember that the template '' can make calls, too.

    
answered by 30.12.2016 в 10:54