JavaScript/Automatic semicolon insertion

From Wikibooks, open books for an open world
Jump to navigation Jump to search
Previous: Lexical structure Index Next: Reserved words

Automatic Semicolon Insertion (ASI)[edit]

In C-like languages, the semicolon denotes the end of a statement. Unlike other C-like languages, JavaScript does not enforce the use of a semicolon at the end of a statement. Instead, the semicolon is optional, and the JavaScript interpreter will "intelligently" add them when it runs the code.

In JavaScript, a semicolon is automatically inserted when [1]

  1. two statements are separated by a line terminator
  2. two statements are separated by a closing brace ('}')
  3. a line terminator follows a break, continue, return, or throw.

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[edit]

Entered code "Understood" as Corrected code
return
2*a + 1;
return;
2*a + 1;
return 2*a + 1;
function getObject() {
  return
  {
    // some lines
  };
}
function getObject() {
  return;
  {
    // some lines
  };
}
function getObject() {
  return {
    // some lines
  };
}
i
++;
i;
++;
i++;
if (i === 5)
  // assuming a semicolon here
else
  foo = 0;
if (i === 5)
  // no semicolon here!
else
  foo = 0;
if (i === 5){
  // code
  } else {
    foo = 0;
  }

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

References[edit]

  1. cjihrig (2012-03-09). "The Dangers of JavaScript’s Automatic Semicolon Insertion" (in English) (HTML). cjihrig.com. Archived from the original on 2012-03-09. http://cjihrig.com/blog/the-dangers-of-javascripts-automatic-semicolon-insertion/. Retrieved 2015-04-03. 

See also[edit]

* Whitespaces & semicolons in JavaScript

Previous: Lexical structure Index Next: Reserved words