Semicolons

By: Dusty Arlia
Published on March 3, 2013
Last Updated on Wednesday, July 15, 2015 at 11:52 AM
Total Updates: 4

Lines of code are normally terminated with semicolons. The semicolon indicates the end of a JavaScript statement. Semicolons act as separators for your statements. These separators make your code easier to read. Without them, it would be hard to tell where one statement ends and where the other begins. Each statement will end with a semicolon (;). The semicolon indicates that the step is over and that the JavaScript interpreter should move on to the next JavaScript statement.

When you accidentally leave out a semicolon, it can possibly break your JavaScript program. It is often a good idea to explicitly terminate statements with semicolons even when they might not be necessary. This is done a lot after closing curly braces (}). There are some instances where semicolons are not necessary, like when your code is the first line of a conditional statement, loop, or function definition.

In the JavaScript programming language, line breaks or carriage returns are known as line terminators. JavaScript treats line breaks as semicolons when the next line cannot be interpreted as a continuation of the previous. There are two exceptions to this rule:

  1. JavaScript always treats line breaks after the return, break, and continue keywords as semicolons.
  2. JavaScript always treats line breaks before the -- and ++ postfix operators as semicolons. Always keep your operator right next to your variable like this: widgets_variable++

For example:

var  message
message = 'WRM readers'
alert('Hello' + message)

In this example, the JavaScript interpreter adds a semicolon to the end of each line of code, because there's no way that these lines could have been interpreted as continuations of each other.

If you have a statement that starts with a ( or a [, you have to watch out for continuation from the previous statement. Use an explicit terminating semicolon at the end of the previous statement if you are unsure of its continuation. Here are all the characters that when used to start a statement, could be interpreted as continuation of the previous statement:

  • /
  • -
  • (
  • +
  • [

You can also proactively defend against continuation by starting your statement with a semicolon (also called a defensive semicolon).

Comments:

Ad:

Ad: