1. Computing & Technology

Semicolons in JavaScript

From , former About.com Guide

The semicolons on the end of statements in JavaScript are optional and your JavaScript will still work if you don't include them. That said there are still a number of very good reasons why you should include them even though they do not absolutely have to be there.

  • Not all semicolons in JavaScript are optional. For example the ones in a for statement must be included or the for statement will give a syntax error. By always including the semicolons you don't have to remember which ones you can and can't leave out.
  • The semicolons on the end of statements are only optional if the statement ends at the end of a line and is followed by a new line character before the next statement starts. By always including the semicolons you make it easier to compress your code by removing unnecessary whitespace.
  • In JavaScript statements can be split across several lines provided that the content of a particular line does not look like a complete statement by itself. By always including the semicolons you provide a visual reminder for yourself of where the statements end and so will be able to see more clearly which statements are split over multiple lines and may therefore be the cause of an error where the entire statement is not being read. One example of this sort of error is where you have the word return on one line and the value to be returned on the next where because a return statement without a value to be returned is valid your code will not be processed correctly.

Allowing semicolons to be optional in JavaScript in the first place was a mistake since it means that the interpreter has to make assumptions as to where statements end and it doesn't always get it right. You can't completely eliminate the problems that optional semicolons introduced into JavaScript by making sure that you always include them but at least you can reduce those problems as much as possible and make your code easier to maintain by making sure that you always include the optional semicolons as well as the mandatory ones.

©2012 About.com. All rights reserved.

A part of The New York Times Company.