Вопрос №25156 от пользователя Ekaterina Lopatina в уроке «Условия и принятия решений», курс «Введение в программирование»
Коллеги, день добрый. Код правильный, тест проходит. Но выводит другие ошибки.
Вот такие ошибки выводит
В чем проблем, помогите разобраться, пожалуйста
Проблема, на мой взгляд начинающего программиста, заключается в том, что при использовании больше одного if, последующая конструкция if должна превратится в else if. То есть перед вторым и третьим if следует прописать слово else. UPD Оказывается (посмотрел решение учителя), что и не нужно тут else if'ов :-). Тогда, что можно сказать, каждый if с новой строки начинать, а не продолжать после > (я так понимаю, ругается на плохую читаемость кода, что if'ы на одном уровне, а то, что выполняется должно быть на другом уровне; а получилось, что второй и третий if заняли места их же return'ов) И удалить пустую строку перед export.
Екатерина, здравствуйте! Это отчёт работы линтера с описаниями стилистических ошибок. Их также нужно всегда исправлять. Давайте разберём, как работать с замечаниями линтера на примере простой ошибки: 9:2 error Missing semicolon semi .
- 9:2 — строка и позиция, где по мнению линтера произошла ошибка;
- Missing semicolon — описание ошибки
- semi — название ошибки
Переведите и проанализируйте описание. При необходимости загуглите по названию ошибки semi eslint и почитайте документацию с примерами. Исправьте ошибку и запустите повторную проверку линтера.
Я понимаю, что это нужно исправлять. Однако, я не понимаю что именно здесь нужно исправлять, ибо:
- 3:6 error Strings must use singlequote quotes\ здесь и не должно быть "строки", почему он ругается что строка должна быть в кавычках?
- 9:2 error Missing semicolon semi\ строка 9, позиция 2 — это перед ">" зачем там ";"?
- 10:1 error Too many blank lines at the end of file. Max of 0 allowed no-multiple-empty-lines\ Если я удаляю последнюю пустую строку, то потом он ругается, что программа запрашивает новую строку, но не может обнаружить
/usr/src/app/finalGrade.js\ 15:27 error Newline required at end of file but not found eol-last
Поэтому я и прошу помощи разобраться, ведь даже запуская решение учителя, выдаются те же ошибки линтера
Ого! Мы разобрали, как работать с линтером на примере ошибок системного файла. К вашему коду они не имеют отношения. Поправил ошибку в среде исполнения. Вам нужно получить последнюю версию практики, нажав кнопку Сброс, и после этого проработать замечания линтера повторно.
Is It Necessary to Use Semicolons in JavaScript?
Let’s start with two basic but very important ideas: 1) JavaScript is a flexible language, and 2) some semicolons in JavaScript are more needed than others. JavaScript sometimes gives us so much freedom that some practices end up being “optional”, and an example of this is the use—or lack of use—of certain semicolons.
To simplify the idea further, normally a missing semicolon won’t break your JavaScript code as it would in another programming language such as Java or the C family, but there’s a catch: Sometimes you can and will break your javascript code for a missing semicolon in the right (or wrong, maybe?) conditions.
How JavaScript works
Before diving into the fun part, a.k.a “how to break your code with the correct missing semicolon,” let’s take a moment to try to better understand how JavaScript as a programming language works in the background.
Compiled vs Interpreted
There are two types of programming languages: compiled and interpreted. Compiled languages need a compiler to turn written code into machine code that will be executed later. Some classic examples of this are languages such as C, C++, and Haskell. On the other side, interpreted languages such as Python or PHP (freecodecamp.org, 2020) are interpreted at runtime. Then we have JavaScript…a language that we cannot definitively classify as neither compiled nor interpreted.
JavaScript defies classification because at a very technical level it is compiled before being interpreted by the browser line by line. This can be tricky to understand and agree on; some classify JavaScript as an interpreted language. For example, this article from Stanford University explicitly states that “JavaScript is an interpreted language, not a compiled language,” and even the same article from freecodecamp.org referenced above classifies JavaScript as an interpreted language. Let’s not forget, however, that the code that is being interpreted by the browser was first compiled by the engine behind it. If we want to verify this information, we can reference the official V8 blog which states the following:
“With Ignition (the interpreter inside V8), V8 compiles JavaScript functions to a concise bytecode, which is between 50% to 25% the size of the equivalent baseline machine code. This bytecode is then executed by a high-performance interpreter which yields execution speeds on real-world websites close to those of code generated by V8’s existing baseline compiler.” (V8 official blog, 2016).
V8 is Google’s JavaScript engine on some browsers like Google Chrome (V8.dev), but if we still have some second thoughts on this whole compiled versus interpreted process, we can take a look at this illustration:
Finally, as we can see in the illustration, during the compile-time also happens something called “parsing”, a process that is in charge of “analyzing and converting a program into an internal format that a runtime environment can actually run” (MDN Docs, 2021), or in other words, this is the translation from the thing we have, into the thing we need to make it work in the browser. Knowing about the step of parsing during the compilation is necessary for you to understand the exact part of the execution that deals with the missing semicolons.
Automatic Semicolon Insertion (ASI)
Now that we know about the relationship between the compiling process, the parsing, and the interpretation of the code in the browser, we are ready to talk about something that happens during the parsing step called Automatic Semicolon Insertion (ASI).
This process inserts semicolons in some statements in the JavaScript code when we don’t do it ourselves. To be more precise these are the statements that will be updated by the ASI (MDN Docs, 2021):
- Empty statement
- Variable statement
- Import & export
- Expression statements
- Debugger
- Continue, break, throw & return
To clarify this idea a little bit more we can take a look at the next illustration with a few simple lines where we can see the before and after the ASI in our code:
There are three explicit rules in the JavaScript architecture for the Automatic Semicolon Insertion (ECMAScript, 2021) that we can keep in mind:
- When there is a line terminator that is not allowed.
- When the parser cannot parse the next line.
- When we have ++, –, continue, break, return, yield, yield* and module.
Again, as we can see on the documentation (ECMAScript, 2021) this is a simple way to represent and understand when the ASI works and when it does not:
But, if you’re still not sure about how true this is, you can reproduce it yourself on the browser’s console like this:
Only the first one didn’t work because of the missing semicolon that the ASI couldn’t add, but the same code with a line terminator (the code on the new line) did work because the ASI was able to fix it.
When to use semicolons
Now that we know that JavaScript automatically adds semicolons to certain statements with a few restrictions and rules, we can—as a best practice—use semicolons after finishing statements such as variable declaration with var, let, or const, when calling a function, using ++ or –, and when using return, break or continue.
Let’s wrap up the “semicolons in JavaScript” topic with some clear examples of when your code will break for a missing semicolon.
In this case, the missing semicolon on the declaration of variable c breaks the following toString function because its value is recognized as a non declared function. We can fix this error with a semicolon in the declaration of the last variable. (Flavio Copes, 2018)
In this case, the error is with the variable c, and that’s because, for JavaScript, the last piece of code is in the same line, it looks like this:
With that being said, we’re trying to use a variable that doesn’t exist yet, and again, the way to fix this behavior is with the almighty semicolon.
Final thoughts
JavaScript is a very flexible language, but that doesn’t mean that we only have to put forth the minimum effort to make it work. As a best practice, we should use standard conventions within our projects, and in these particular cases, that convention should include using semicolons because even if you don’t add them, the language needs them anyway and will try—but not always succeed—to fix them with ASI.
It is important to keep in mind two more things: First, it’s possible to have errors if you don’t use semicolons in your JavaScript file and try to minify or uglify it. Second, semicolons will not significantly affect the performance and size of your file (Fullstack Academy, 2017).
Your code will not always break due to a missing semicolon, but contrary to popular belief, JavaScript is relying on them in the background. As developers, it is our responsibility to understand the behind-scenes process of the tool we’re using.
SyntaxError: missing ; before statement
The JavaScript exception «missing ; before statement» occurs when there is a semicolon ( ; ) missing somewhere and can’t be added by automatic semicolon insertion (ASI). You need to provide a semicolon, so that JavaScript can parse the source code correctly.
Message
Error type
What went wrong?
There is a semicolon ( ; ) missing somewhere. JavaScript statements must be terminated with semicolons. Some of them are affected by automatic semicolon insertion (ASI), but in this case you need to provide a semicolon, so that JavaScript can parse the source code correctly.
However, oftentimes, this error is only a consequence of another error, like not escaping strings properly, or using var wrongly. You might also have too many parenthesis somewhere. Carefully check the syntax when this error is thrown.
Examples
Unescaped strings
This error can occur easily when not escaping strings properly and the JavaScript engine is expecting the end of your string already. For example:
You can use double quotes, or escape the apostrophe:
Declaring properties with var
You cannot declare properties of an object or array with a var declaration.
Instead, omit the var keyword:
Bad keywords
If you come from another programming language, it is also common to use keywords that don’t mean the same or have no meaning at all in javaScript:
JavaScript Semicolons are Bad, Actually
I’ve been lured into the no-semicolon club. I didn’t expect to be convinced, but I had missed a truly compelling argument.
Let’s start with some background to illustrate why this debate even exists.
automatic semicolon insertion is the well-defined (but oft confusing) process by which a JavaScript parser interprets \n as being the end of a statement.
Rules
Taken from a description by Isaac Schlueter (and quoted on this eslint rule):
a newline character always ends a statement, just like a semicolon, except where one of the following is true:
— The statement has an unclosed paren, array literal, or object literal or ends in some other way that is not a valid way to end a statement. (For instance, ending with . or , .)
— The line is — or ++ (in which case it will decrement/increment the next token.)
— It is a for() , while() , do, if() , or else , and there is no <
— The next line starts with [ , ( , + , * , / , — , , , . , or some other binary operator that can only be found between two tokens in a single expression.
ASI Hazards
ASI hazards are scenarios where automatic semicolon insertion causes behavior that would be unexpected to the programmer. The prototypical example of this is
You might expect this to be execute the function on line 3, but line 1 was never terminated. Instead, it will attempt to call <> with function() <. >and then call the return as a function. The result is a runtime error with an error message seemingly unrelated to the code changes.
The illusion of safety
In the past, I’ve been told that when it comes to semicolons in JavaScript, “better to be safe than sorry.” This presupposes that:
using semicolons will prevent you from having bugs related to ASI
Is this statement true?
I’m not sure it is. Will using semicolons in every location where you would like a statement to end, prevent a statement from ending when you did not intend?
No. for counter example, this function will always return undefined
ASI Hazards still exist for developers who use semicolons every time they intend to end a statement. This demonstrates the importance of understanding ASI for JavaScript Developers, even if they diligently use semicolons.
It would seem that even if you’re “safe” you can still be “sorry.”
Can linting save us?
EsLint Semi: ‘error’, ‘always’
let’s look at how our two examples above interact with a common eslint rule.
unintendedMultiline
if you run eslint against the unintendedMultiline example above, these are the errors:
3:1 — no-unexpected-multiline
5:5 — Missing Semicolon
running eslint —fix produces
unintendedSingleLine
if you run eslint against the unintendedSingleLine example above, these are the errors:
running eslint —fix produces
The result is an error that is masked by the linter and might make its way into production.
EsLint Semi: ‘error’, ‘never’
Alternatively, let’s look at how the scenarios above behave when semicolons are not allowed
unintendedMultiline
if you run eslint against the unintendedMultiline example above, these are the errors:
none of the issues are fixable.
unintendedSingleLine
if you run eslint against the unintendedSingleline example above, there are no errors.
With this rule, the programmer is required to understand the behaviors of ASI, but the inability to use semicolons requires more frequent use and understanding of this required knowledge.
Conclusions
ASI cannot be ignored — even by programmers who do use semicolons.
A developer can still run into ASI hazards while using semicolons; you cannot arbitrarily break a line like you can in Java/C++; and ambiguity will always exist between a programmer that intended a multiline statement and one that simply forgot a semicolon.
My primary takeaway is: it’s more valuable to write code that lacks ambiguity in-spite of ASI than to spend time adding semicolons to guard against it.