Pacific Side

Pacific Side

Global Affairs, History, Philosophy, Literature, and the Glocalization of the Internet

20 March 2008

JavaScript and the Semicolon

Until today, I’d never really delved into when and when not to use a semicolon to close a line in JavaScript. I used to use them excessively, which is safe, but recently tried abandoning the semicolon after all closing brackets (“}”). This apparently broke some of my code today though, and I discovered that I need to keep the semicolon after the closing bracket of function expressions, while it is safe to leave it out after the closing bracket of a function statement. The different usage being illustrated here:

// Function expression

var myFunction = function(...) {
    ...
};

// Function statement

function myFunction(...) {
    ...
}

Not having a semicolon after a function statement is ok as long as you have a newline. In a situation where we compress a js file for savings of space, using a program like yui compressor, it can cause errors. For example, try this on firebug console:

fn=function(){console.log("hi");}a=2;

this will show an error.

Insert a semicolon after } and it will work fine.

Rewrite the function expression in there as a statement and it works!

function fn(){console.log("hi");}a=2;

If you plan on posting code, please enclose it in the <pre><code> tags to preserve formatting. If your code block includes HTML tags, please use Postable.

Language

Archives

Categories

Trevor Powell © 2010. All rights reserved.