Home > Enterprise >  Why the error if semicolon not available?
Why the error if semicolon not available?

Time:04-02

It is a very simple IIFE situation in JavaScript.
But the semicolon at the end of the first line will make a huge difference whether it is over there or not.

Here is the error version and no semicolon in the first line:

const obj = {}
(function () { })()

And Chrome complains that:

Uncaught TypeError: {} is not a function

How does browser read this code?

If we add semicolon at the end of that line, error dismissed:

const obj = {};
(function () { })()

I was told that semicolon is not necessary in JavaScript but it apparently is wrong in this situation. Why?

CodePudding user response:

The semicolons in JavaScript are optional, but sometimes missing semicolon can produce error.

In your case, the const obj = {} can be in multiline as well as follow:

const obj = {
}

So, javascript doesn't actually knows when your executional statement has been ended or not. As a result, javascript considers const obj = {} (function() {})() as a single statement, which produces error.
Whereas, when you put a semicolon, you explicitly specifies that the statement ended here, hence const obj = {} and (function() {})() as a separate statements.

This is also discussed at https://eslint.org/docs/rules/semi

CodePudding user response:

From ECMAScript® Language Specification:

12.9.3.1 Interesting Cases of Automatic Semicolon Insertion in Statement Lists

In a StatementList, many StatementListItems end in semicolons, which may be omitted using automatic semicolon insertion. As a consequence of the rules above, at the end of a line ending an expression, a semicolon is required if the following line begins with any of the following:

  • An opening parenthesis ((). Without a semicolon, the two lines together are treated as a CallExpression.

  • An opening square bracket ([). Without a semicolon, the two lines together are treated as property access, rather than an ArrayLiteral or ArrayAssignmentPattern.

  • A template literal (`). Without a semicolon, the two lines together are interpreted as a tagged Template (13.3.11), with the previous expression as the MemberExpression.

  • Unary or -. Without a semicolon, the two lines together are interpreted as a usage of the corresponding binary operator.

  • A RegExp literal. Without a semicolon, the two lines together may be parsed instead as the / MultiplicativeOperator, for example if the RegExp has flags.

  • Related