Use semicolon or not at the end of the lines in Javascript?

Asked

Viewed 12,436 times

66

I have read some comments on the web about whether or not to use the ; at the end of the lines when writing Javascript. Some say yes, others say no need, but none can explain well the reasons for the differences.

Example:

var ola = "Olá";     // Com ponto e vírgula.
var mundo = "Mundo"  // Sem ponto e vírgula.

The interesting thing is that even eventually forgetting the ; in my code, it continues running smoothly and without shooting errors. So, the correct is to use or not the famous semicolon?

  • 2

    If you want to delve into the subject, I recommend two books: Javascript Patterns, by Stoyan Stefanov, and Maintainable Javascript, by Nicholas Zakas. The presence or absence of the semicolon can change the meaning of an instruction. Otherwise, it is good practice to use it because it makes the code more readable.

7 answers

56


Always use the ; and this is why:

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

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

Thank you to @Gabriel Gartz for warning that any logical, mathematical or scoping operator can generate the code execution equally.

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

Let’s see with examples:

Carry out an alert without the declaration separator ;:

alert("olá")

Everything goes as expected, we received an alert.

Perform two alerts without the declaration separator, but each alert on your line separated so by "end-of-line":

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

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

Everything goes as expected, we received two alerts.

Perform two separate alerts with the declaration tab ;:

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

Everything goes as expected, we received two alerts.

Perform two alerts without the separation statements ; and with the compressed code:

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

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

SyntaxError: missing ; before statement
 
alert("olá")alert("olá novamente")

Based on @Gabriel Gartz’s reminder, it can be verified that if the syntax is correct, the code is executed without errors, even if the declarations are separated by something other than the ;:

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

Will generate three alerts as expected.


Automatic semicolon insertion (;)

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

Statement Example of the Declaration
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 statements that must be completed with the declaration tab ;, reason why they receive automatic insertion of it if it is not found.

What are the rules for this to happen:

The code is read from left to right. If a symbol offensive that is not permitted in any production of grammar, automatic insertion of a semicolon occurs if one of the following conditions is true:

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

Notes:

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

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

Documentation: 7.9 Automatic Semicolon Insertion (English)

  • It would be nice to add a note saying that the semicolon also becomes a statement when it does nothing, sample guide.

  • Tagged statements also receive semicolon (;), for example: etiqueta: 6 ;.

13

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

A case like:

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

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

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

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

If there is no instruction body to run a semicolon should be added, otherwise a block like:

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

Will be interpreted as:

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

Therefore, 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 instruction in the same row it is mandatory to use a semicolon.

var i; i = 42

11

I recommend reading this article by Caio Gondim, because non-use can cause several situations and it is good to understand each one of them.

http://loopinfinito.com.br/2013/10/22/mamilos-pontos-e-virgulas-em-js/

In summary [...] the ; serves as a statement delimiter. But due to the ASI, the \n will also function as statement delimiter, except in the following cases:

1 - The statement has a parenthesis, literal array or unopened literal object or ends any other way that is not a valid way to end a statement.
2 - The whole line is a -- or ++ (in this case, will increment/decrease the next token)
3 - It is a 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 above 4 situations the ASI will not be triggered, in other situations the ASI will normally interpret the \n as delimiter.

7

Zuul’s answer is the correct one. I’m just going to leave a specific case here because no one has so far commented on:

This:

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

Is equivalent to this:

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

Come on, run both forms on your browser console ;)

And if you don’t pay attention to that fact, you can make mistakes more often.

Using semicolons is not mandatory, but it is good practice because it makes it clearer where one expression ends and another begins.

7

All the good programmers I know use it. Because it’s ambiguous not to use it in some situations. And if you need to use it on some it’s weird not to use it on others. And you start to create a dialect of the language between those who use it and those who don’t.

There is no gain in not using. In general it is adopted by those who think that tapping the finger on a key gives a gain, but leaves the doubt whether it really ended the statement there, because there are cases that he can continue in another line. Makes it difficult to read all in all cases to save effort of a typed key.

Some say that without it it saves a byte to transmit. I find a gain too small to compensate for the problem. In general people spend a lot more on other things, and if you’re going to use that argument, all code should be written in a very unreadable way to save bytes. The economy should come more than one compression (static file should always be compressed) and minification (good mini-finishers should take the comma where gives and leave where you need or may need, but many do not make it so complicated is parse JS code for allowing this kind of thing, some minifica less precisely by the lack of a semicolon, so it’s a very wrong reason). And today JS is very used in backend that it makes no sense to have that kind of concern. Again, it will create two dialects?

I’ve seen people say it’s easier to insert something in the middle, especially using method chaining, but it only shows that the motive is laziness, a wrong motive.

Javascript was created to have a syntax similar to C, some even think it bad, but it was thought so, so the ; is important, even if the compiler lets, in some cases do not use. If you are used to continue using.

Turn and move someone comes up with a problem because they didn’t have the ; and the behavior gets strange (some cases make mistakes, others only do what does not expect).

There are languages that have been able to make the use optional in an unambiguous way, that’s fine, but it’s not the case of JS.

In fact they put the ; for you, JS also does this, but it has no rules as clear, and even differs from implementation to implementation. So don’t do this to yourself, even if it works most of the time. So I’m not going to put the rules like some people do because whoever creates a language compiler doesn’t understand the rules, they always post about simple rules and... wrong.

inserir a descrição da imagem aqui

For the same reason I don’t like:

if (x == 1)
    console.log("ok");

Or does:

if (x == 1) console.log("ok");

because there is a line, not confusing with a block, or does:

if (x == 1) {
    console.log("ok");
}

This can cause problems when you put more than one line in the unclear condition of what the block is.

The problems you will have are not so relevant, but they exist. I think the biggest reason to always adopt the ; is consistency and readability, but I will cite examples of problems.

A example of question that seemed here.

Example in Soen.

Example:

const hey = 'ola'
const you = 'ola'
const heyYou = hey + ' ' + you
['o', 'l', 'a'].forEach((letter) => console.log(letter))

Now writing right:

const hey = 'ola';
const you = 'ola';
const heyYou = hey + ' ' + you;
['o', 'l', 'a'].forEach((letter) => console.log(letter));

Other:

const x = 1
const y = 1
const z = x + y
(x + y).toString()

I’m not gonna post the right one at all, fix you up by putting the ;.

var x = 1 + 1
-1 + 1 === 0 ? console.log("sim") : console.log("não")

I do not like some examples of the other answers (not all), for example I do not like the answer accepted because it is an example that is clearly mandatory, the problem is not to omit the ; in the same line, but yes when it changes lines. Although at the time I had positive together with two others. The answer is good, well thought out, and correct, but I could have a better example.

Complement.

5

The point and comma in Javascript is used to force the interpretation of the syntax in a line, delimiting this execution to the passage that precedes the point and comma.

You are not required to use the point and comma to delimit an execution, there are other ways, such as logical operators or scope definitions, but it is good practice to use the point and comma.

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

Example:

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

It will execute first the function that creates an alert with foo and then with alert that displays bar

The same result can be obtained with the operator & 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 its syntax and will expose an error with 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 nothing more than the curiosity of JSC, the recommended is that you always use the point and comma to delimit the interpretation of your syntax.

4

First I would like to point out that the semicolon sometimes separates statements (when I refer to 'statements' I refer to statements, utterances and other instructions that may appear in ordinary bodies), but on other occasions, becomes a statement that does nothing. For example, the Ecmascript3 label requires a statement on the front (and the appropriate label declaration name is LabelledStatement (Or LabeledStatement):

/* 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 semicolon (semicolon and semicolon) can appear in any unused space of a body of statements, even at the top (see in Esprima):

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

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

Strange is doing it in a language like Actionscript 3, and still working!

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

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

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

Or it is also possible to 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. Remembering that the template `` can make calls, too.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.