Missing Semicolons in JavaScript can be very unproductive
MyClass.prototype.myMethod = function() <
return 42;
> // No semicolon here.
(function() <
// Some initialization code
// wrapped in a function to
// create a scope for locals.
>)();
==> The function returning 42 is called with the second function as a parameter, then the number 42 is “called” resulting in an error.
// Trying to do one thing on Internet Explorer and another on Firefox.
==> You will most likely get a ‘no such property in undefined’ error at runtime as it tries to call x[ffVersion, ieVersion][isIE]().
var THINGS_TO_EAT = [apples, oysters, sprayOnCheese] // No semicolon here.
// conditional execution a la bash
-1 == resultOfOperation() || die();
==> die is always called since the array minus 1 is NaN which is never equal to anything (not even if resultOfOperation() returns NaN) and THINGS_TO_EAT gets assigned the result of die().
==> the example is interpreted in the same way as:
a = b / hi / g.exec(c).map(d);
JavaScript requires statements to end with a semicolon, except when it thinks it can safely infer their existence. In each of these examples, a function declaration or object or array literal is used inside a statement. The closing brackets are not enough to signal the end of the statement. JavaScript never ends a statement if the next token is an infix or bracket operator.
This has really surprised people, so make sure your assignments end with semicolons. Semicolons should be included at the end of function expressions, but not at the end of function declarations. The distinction is best illustrated with an example:
JavaScript Error Handling – SyntaxError: missing ; before statement
As we march along through our JavaScript Error Handling series, today we’ll be parading our way through the Missing Semicolon Before Statement JavaScript error. As the name implies, the Missing Semicolon Before Statement error is typically thrown when a semicolon ( ; ) was forgotten somewhere in the code.
In this article we’ll go over the Missing Semicolon Before Statement error in more detail, including where it resides within the JavaScript Exception hierarchy, and what possible causes could produce a Missing Semicolon Before Statement error in the first place. Let’s get this band a’steppin!
The Technical Rundown
When Should You Use It?
A Missing Semicolon Before Statement error, on the face of it, means that the JavaScript engine expected a semicolon ( ; ), yet none was provided. There are many cases where this might occur, ranging from actually forgetting to add a semicolon where needed, to other errors or syntax issues that would accidentally cause a Missing Semicolon Before Statement error instead.
As a general rule, JavaScript statements must (almost) always be terminated by a semicolon. The final semicolon is a simple way for the parsing JavaScript engine to determine when a statement both starts and finishes, so it can easily evaluate what should be executed and what should be separate from other code statements.
In practice, this manifests itself when JavaScript interprets a typical line break as including a semicolon, even where one doesn’t exist. For example, here we’re using the var keyword to initialize a variable without a closing semicolon:
This is no problem, because the automatic semicolon insertion ( ASI ) notices our var keyword as the beginning of a statement, and thus it automatically inserts a closing semicolon when it reaches the end of the line. From the perspective of the JavaScript engine, the above code looks like this:
In fact, we can rewrite our original example to be even more abstract, with a line break after every element:
With a basic understanding of how JavaScript understands semicolons, we can tackle the Missing Semicolon Before Statement error. As a simple example, what happens if don’t abide by the ASI rules and try to assign a function to our getFullName variable, without remembering the function keyword, like so:
JavaScript is not too happy with this, and throws a Missing Semicolon Before Statement error (in Firefox at least, Chrome parses it slightly differently):
To dive even deeper into understanding how your applications deal with JavaScript Errors, check out the revolutionary Airbrake JavaScript error tracking tool for real-time alerts and instantaneous insight into what went wrong with your JavaScript code.
Monitor Your App Free for 30 Days
Discover the power of Airbrake by starting a free 30-day trial of Airbrake. Quick sign-up, no credit card required. Get started.
Вопрос №25156 от пользователя Ekaterina Lopatina в уроке «Условия и принятия решений», курс «Введение в программирование»
Коллеги, день добрый. Код правильный, тест проходит. Но выводит другие ошибки.
Вот такие ошибки выводит
В чем проблем, помогите разобраться, пожалуйста
Проблема, на мой взгляд начинающего программиста, заключается в том, что при использовании больше одного if, последующая конструкция if должна превратится в else if. То есть перед вторым и третьим if следует прописать слово else. UPD Оказывается (посмотрел решение учителя), что и не нужно тут else if’ов :-). Тогда, что можно сказать, каждый if с новой строки начинать, а не продолжать после > (я так понимаю, ругается на плохую читаемость кода, что if’ы на одном уровне, а то, что выполняется должно быть на другом уровне; а получилось, что второй и третий if заняли места их же return’ов) И удалить пустую строку перед export.
Переведите и проанализируйте описание. При необходимости загуглите по названию ошибки semi eslint и почитайте документацию с примерами. Исправьте ошибку и запустите повторную проверку линтера.
Я понимаю, что это нужно исправлять. Однако, я не понимаю что именно здесь нужно исправлять, ибо:
/usr/src/app/finalGrade.js\ 15:27 error Newline required at end of file but not found eol-last
Поэтому я и прошу помощи разобраться, ведь даже запуская решение учителя, выдаются те же ошибки линтера
Ого! Мы разобрали, как работать с линтером на примере ошибок системного файла. К вашему коду они не имеют отношения. Поправил ошибку в среде исполнения. Вам нужно получить последнюю версию практики, нажав кнопку Сброс, и после этого проработать замечания линтера повторно.
semi reports missing semicolon on export default class #2194
Comments
btmills commented Mar 30, 2015
Looks like similar cases were addressed in #2178 and this one was missed.
The text was updated successfully, but these errors were encountered:
nzakas commented Mar 30, 2015
Imports/exports have so many variations, it’s crazy. 🙂
pola88 commented Apr 1, 2015
I have a problem with export as well.
My problem is the following:
and I get error Missing semicolon semi
if I add the semicolon, returns:
Do you know how fix it?
Thanks,
btmills commented Apr 1, 2015
Working on this. It’s quite the bear. In the meantime, this is my interpretation of the spec, broken down by the productions of ExportDeclaration :
export * FromClause ;
export ExportClause FromClause ;
export ExportClause ;
export VariableStatement
export Declaration
Declaration : HoistableDeclaration
Declaration : ClassDeclaration
Declaration : LexicalDeclaration
Semicolon belongs to LexicalDeclaration.
export default HoistableDeclaration
export default ClassDeclaration
export default AssignmentExpression ;
Semicolon belongs to ExportDeclaration.
tl;dr:
I find this interesting, from ESTree:
Note: Having declaration populated with non-empty specifiers or non-null source results in an invalid state.
Edit: ExportDefaultDeclaration may have a semicolon if its child is an expression.
Missed semicolon error in combination with dynamic components and Moment.js #1968
Comments
lukasleitsch commented Jan 30, 2019 •
Description:
If I import the moment library in a dynamic component I will get an error in the production build process. I found a workaround to avoid the error. In the steps to reproduce section, I will explain it in detail. The error only appears in the production build process ( yarn run production ). The dev build process ( yarn run dev ) runs without any errors.
I don’t know which component actually cause the issue. I hope you can help me to get rid of the workaround.
Steps To Reproduce:
Replace the line Vue.component(‘example-component’, require(‘./components/ExampleComponent.vue’).default); with Vue.component(‘example-component’, import(‘./components/ExampleComponent.vue’)); in the file resources/js/app.js
Add import moment from ‘moment’; in the script tags of resources/js/components/ExampleComponent.vue
Run yarn run production
The build process crash with the error «CssSyntaxError: /css/app.css:3:13: Missed semicolon»
If I add the import import moment from ‘moment’; into the first line of resources/js/app.js the build process works without the issue. This workaround is not really nice because the moment lib than also lives in the app.js and not only in the chunk of the component.
CssSyntaxError: /css/app.css:3:13: Missed semicolon
The text was updated successfully, but these errors were encountered:




