JavaScript/Automatic semicolon insertion


Automatic Semicolon Insertion (ASI)

In C-like languages, the semicolon denotes the end of a statement. Unlike other C-like languages, JS doesn't enforce that. Instead, the semicolon is optional, and the interpreter adds missing semicolons - mostly at the end of a line - to terminate statements. Doing so, he takes complex rules into account. This may conflict with the intended purpose.

If you write your code without semicolons at the end of statements, you must take care of problematic situations. Here are some rules-of-thumb to avoid problems. But there are much more rules.

  1. The expression after one of the keywords return, throw, or yield must be on the same line as the keyword itself.
  2. The label identifier after break or continue must be on the same line as the keyword.
  3. If a line starts with one of (, [, `, +, -, or /, end the previous line with a semicolon.

While ASI would make your code easier to write (no need to type all of those semicolons), in practice, the lack of semicolons makes your program harder to debug. Because of this, it is universally recognized as a best practice to use semicolons at the end of statements anyway. However, the existence of ASI can still create some bugs that are hard to troubleshoot if you don't know what to look for.


Examples

Entered code .. .. interpreted as intended code
return
2a + 1
return;
2a + 1;
return 2*a + 1;
function getObject() {
  return
  {
    // some lines
  }
function getObject() {
  return;
  {
    // some lines
  };
}
function getObject() {
  return {
    // some lines
  };
}
i
++
i;
++;
i++;


In the first case, the programmer intended 2*a + 1 to be returned; instead, the code returned undefined. Similarly, in the second case, the programmer intended to return the lines enclosed by the braces {}, but the code returned undefined. Due to this oddity in JavaScript, it is considered a best practice never to have lines break within a statement and never have the opening brace on a separate line.

See alsoEdit