Why does the exchange of values via de-structuring not work if we do not use semicolons?

Asked

Viewed 286 times

12

We know that the semicolon is optional in Javascript, even always prefer not to use it. If I want to exchange values between two variables, via unstructuring, I can do:

let a = 11;
let b = 22;
[a, b] = [b, a]
console.log(a, b)

This code snippet works exactly as expected and performs the exchange of values between the variables a and b without the need for an auxiliary variable.

However, if I do not use semicolon in the declaration of the variables that will participate in the exchange, as below, an error occurs:

let a = 11
let b = 22
[a, b] = [b, a]
console.log(a, b)

Simply gives error. The error message is "Uncaught ReferenceError: Cannot access 'b' before initialization". Why does this behavior occur when we do not use the semicolon in the declaration of variables?

  • @Pedrohenrique in JS is yes, the language automatically inserts, the problem in this case is that the ; is being inserted in the wrong place

  • found this link which explains the reason for the error

  • Well, the official documentation says that the semicolon is, yes, optional. https://www.ecma-international.org/ecma-262/5.1/#sec-7.9

  • 5

    @Denisrudneidesouza that is something I have said several times, there were people who even denied my answer because I said that should always use the ; even if you don’t have to. It’s really optional, it just doesn’t mean it’ll be put in the right place, the compiler isn’t able to solve all cases. There is a wave of people teaching not by ; in JS, what is a mistake, an hour bursts. This is the typical situation of this: https://i.stack.Imgur.com/td2dx.jpg https://g1.globo.com/sp/sao-paulo/noticia/2019/07/10/prefeito-e-primeira-damade-osasco-tem-alta-12-dias-apos-exploso-de-fogueira.ghtml

  • 1

    Optional is, but it’s always good to use.

  • I see no reason to be negative, it is optional, sometimes it does not work as expected, guide to put where possible is good advice

  • 4

    @Denisrudneiuza will answer? Continuing the previous comment: ignorance + arrogance is an explosive combination, the person sees happening right once, another, one more, then others, always works and he starts to believe it is true, that is, he creates fake news for herself. Because she doesn’t want to see what’s right. Yes, she may not ;, but it should not, the language was not well defined for it always work. So make no exception, always do the right thing, which is guaranteed to work. That’s not what happened in Osasco. Because it worked before they believed nothing would happen.

  • @Maniero I will not reply, I put the comment just for more information, I do not know how to formulate a good answer to this case

Show 3 more comments

2 answers

14


It is precisely because of this type of thing that the semicolon should always be used. To avoid this type of error in the code. It’s a kind of laziness that can cause mistakes.


In Javascript, every statement (statement) shall be completed by a semicolon. To ensure that this is always the case, even if the programmer forgets this ending, the language has a mechanism called "automatic semicolon insertion", or "Automatic semicolon Insertion", which makes insertion of most semicolons optional. So this mechanism basically fixes syntax errors by inserting the semicolons that the programmer omitted.

The language specification determines that automatic semicolon insertion must follow three rules to happen. In a large summary, the three rules determine that a semicolon shall be inserted in the following cases::

  1. When the program finds a token offensive (offending token), a semicolon is inserted. A offending token is basically something that is not correct according to the grammar of the language.
  2. When the end of the input flow of tokens is found (the end of the program), a semicolon is inserted.
  3. When a return, continue, break or throw is found and then find yourself a LineTerminator and a Restricted token, as a }, a semicolon will be inserted before the Restricted token.

I tried to summarize it in the best way possible. See specification for more details on these steps.

With this, it is possible to say that in his example:

let a = 11
let b = 22
[a, b] = [b, a]

A semicolon will be inserted after 11, since l (following 11) would be considered a offending token (rule number one). However, a semicolon shall not be inserted after 22 automatically, since it does not fit any of the above rules. It is an "ambiguous" case for the compiler, and therefore it will not insert the semicolon.

It is possible to understand why with the following code:

const myArray22 = ['A', 'B', 'C'];

// Note que depois de `22`, `[` é um token válido.
const x = myArray22
[0];

console.log(x); // A

It is possible to confirm that the character [ was not seen as a offending token, and therefore a semicolon has not been inserted.


This is one of several examples in which the Automatic semicolon insertion is not 100% accurate, and therefore many recommend that it should always be used. Tools like Eslint, with the rule semi; or the Prettier can help you immeasurably with that.

Reference

Resources I used while drafting this answer:

  • 2

    I found a dirty negative in the reply. As it came along with a positive in mine may be some fan. I do not support this. I even think that this answer better answers the specific question and I think the acceptance is fair. And if someone thinks I was the one who denied it I can even prove that I didn’t vote (not only with screenshot that you can Photoshop :) ), I can do a lot of things that people don’t like, but not negative good content.

  • 1

    I would also like to know why the negative (I always like to know when I receive a T_T). But @Maniero, don’t worry, you are one of the last people I would "distrust", since I’m sure you are one of those who really know how to use the voting system correctly. :-)

11

Javascript has chosen to specify in the language that the ;, which means the end of a statement, could be optional in code. Contrary to what many think, it’s not that you don’t need the semicolon, it’s that the compiler puts it to you.

In order for the compiler to be able to do this, it needs clear, unambiguous rules where to place it. It’s not easy to do this, it’s even harder when you add a Feature new in language (which I think the case was just this, the key before was treated as a case that should not start a new statement, could not change this not to break compatibility, then created a case that was necessary, and the error happened). So it doesn’t always work well, there’s a situation that the compiler can’t put in the right place or even put where it should. In this case what happened was this:

let a = 11; let b = 22 [a, b] = [b, a]; console.log(a, b);

I put in the Github for future reference.

He put it in some places, but did not understand that the disintegration was another statement, Then it was like it was one thing. Then the error became strange, for him what has there is to use a variable that has not yet been defined because the definition only occurs at the end of statement, which has not yet occurred when using the variable, let b = 22 [a, b] = [b, a]; is just one statement. That is documented.

Has specification of where it is inserted. But you always have to look at the newer version, because that can change from version to version. So for you to use it right, you have to always take care of it, know what version you’re using. Try to understand and see if it’s worth decoding all that to make it right in each situation.

You can understand the rules simply and solve for one case, but it may not happen for others. It’s not easy to maintain consistency.

So far I’ve explained why this is happening, now let’s understand the roll that people are getting into.

Disregards that the ; is optional

Now, isn’t it easier to stop using these exceptions and put this ; at every end of statement? What’s in it for you if you don’t put it on? The programmer who thinks he is having some gain because he did not need to tap a key there really is in the wrong profession. It’s more work making an exception than always, you have to wonder if you’re right or not. Some people can waste hours not understanding what’s going on. And it may not be you, it may be someone else who will maintain and puts something that doesn’t work because the code that was already written is without the semicolon.

Treating something as an exception during coding generates unnecessary cognitive load. You don’t need it, don’t do it.

Unfortunately there is a wave of people teaching JS without the ;. These people are doing everyone a disservice. It is their right and the misfortune of those who trust them. Just don’t say there’s no warning, and it’s not just me, most good professionals do it.

Anedotically the case of the Osasco bonfire.

Fogueira que explodiu em Osasco

For years the person made fires. Never studied for it, always worked and was always hired by authorities to do that. And of course, because it is an event of authority they found themselves in the right not to consult qualified people on the subject as happens a lot in Brazil (I meant that it is only in the public sector, but it is generalized, not all, but it is common Brazilian to have commitment to error). One hour the bonfire explodes. And only happens because there is a mixture of ignorance and arrogance.

People see working without ; and they think it’s always like this, they come to believe that it’s okay, and they defend it, until it explodes.

This case was easy and obvious, but there is a case that can make the person pull their hair out trying to find out what is happening.

Interestingly, as far as I know, Go does the same and everything works, the rules are clearer and the compiler can do it anyway. But I may be mistaken or have become obsolete with new versions, I am not normal Go user.

Browser other questions tagged

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