user1349313
user1349313

Reputation: 143

Why does code without a semicolon still work in JavaScript?

How come in JavaScript you can call a function without ;?

Example

Let’s say testMethod is declared somewhere...

testMethod();

testMethod() // Without semicolon will still work.

Also calling a method within an element example:

<input type="button" onclick="testMethod();" />
<input type="button" onclick="testMethod()" /> // Again no semicolon.

Upvotes: 3

Views: 8927

Answers (3)

jbabey
jbabey

Reputation: 46647

JavaScript interpreters will add semicolons for you. Omitting semicolons is a very bad idea as it can cause interpreted JavaScript code to behave differently than you'd expect due to this.

See the breaking examples on Wikipedia:

return
a + b;

// Returns undefined. Treated as:
//   return;
//   a + b;

Related:

Do you recommend using semicolons after every statement in JavaScript?

Upvotes: 1

jmar777
jmar777

Reputation: 39649

It's a feature called "Automatic Semicolon Insertion" (or ASI).

From Dealing with JavaScript's Automatic Semicolon Insertion

So how are these semicolons inserted for you? By following these rules (paraphrased and simplified from ECMA-262 3rd edition, 7.9.1):

  • When, as the program is parsed, a token (called the offending token) is encountered that is not allowed by any production of the grammar, then a semicolon is automatically inserted before the offending token if one or more of the following conditions is true:
    1. The offending token is separated from the previous token by at least one LineTerminator.
    2. The offending token is }.
  • When the end of the input stream of tokens is encountered and the parser is unable to parse the input token stream as a single complete program, then a semicolon is automatically inserted at the end of the input stream.
  • A token is a restricted token when it is allowed by some production of the grammar, but the production is a restricted production and the token would be the first token for a terminal or nonterminal immediately following the annotation “[no LineTerminator here]” within the production.

If furthermore the restricted token is separated from the previous token by at least one LineTerminator, then a semicolon is automatically inserted before the restricted token.

...

Upvotes: 32

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340708

Because the JavaScript engine places semicolons at the end of line if it thinks they should have been there. This often introduces bugs rather than avoiding them:

return
{
  user: 'foo'
}

The return statement above returns... nothing:

return;
{
  user: 'foo'
}

Upvotes: 1

Related Questions