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(...) {
...
}
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:
this will show an error.
Insert a semicolon after } and it will work fine.
Trevor
20 March 2008 at 4:07pm
Rewrite the function expression in there as a statement and it works!