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(...) {
    ...
}

2 Responses to “JavaScript and the Semicolon”

  1. joy

    20 March 2008 at 2:05pm

    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.

  2. Trevor

    20 March 2008 at 4:07pm

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

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

Leave a Reply

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