Automatic Semicolon Insertion

The automatic semicolon insertion (ASI)

In C-like languages, the semicolon denotes the end of a statement. Unlike other C-like languages, JavaScript does not always enforce the use of a semicolon at the end of a statement. Rather, a carriage return may be "understood" as a missing semicolon, resulting in different semantics.

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.

Examples

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

  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

* Whitespaces & semicolons in JavaScript


  This article uses material from the Wikipedia page available here. It is released under the Creative Commons Attribution-Share-Alike License 3.0.

JavaScript/Automatic_semicolon_insertion
 



 

Connect with defaultLogic
What We've Done
Led Digital Marketing Efforts of Top 500 e-Retailers.
Worked with Top Brands at Leading Agencies.
Successfully Managed Over $50 million in Digital Ad Spend.
Developed Strategies and Processes that Enabled Brands to Grow During an Economic Downturn.
Taught Advanced Internet Marketing Strategies at the graduate level.


Manage research, learning and skills at defaultLogic. Create an account using LinkedIn or facebook to manage and organize your Digital Marketing and Technology knowledge. defaultLogic works like a shopping cart for information -- helping you to save, discuss and share.

Visit defaultLogic's partner sites below:
PopFlock.com : Music Genres | Musicians | Musical Instruments | Music Industry
NCR Works : Retail Banking | Restaurant Industry | Retail Industry | Hospitality Industry

  Contact Us