Jump to content

JavaScript/Automatic semicolon insertion

From Wikibooks, open books for an open world




Automatic Semicolon Insertion (ASI)

In languages of the C-family, the semicolon denotes the end of a statement. Unlike other C-like languages, JavaScript 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, it 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 many 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.
    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 also

[edit | edit source]