When semicolons are NOT optional in JavaScript

July 22nd, 2009

An inadvertently skipped semicolon recently left me scratching my head over a runtime error. The code looked something like this:

// Add a new function to an existing namespace
some.namespace.doSomething = function () {
    // ...
}

// Define more functions inside a closure to hide some helpers
(function () {
    // ...
})();

This was giving me a “yada yada yada … is not a function” error. In despair, I commented out the closure at the cost of polluting the global namespace! I recently revisited the code (taking a break always helps) and noticed that I was missing a semicolon after the initial function definition:

// Add a new function to an existing namespace
some.namespace.doSomething = function () {
    // ...
}; // <---------------------- AH-HA!

Now, why is this semicolon so important? Let's look at how the code reads without the semicolon, after removing some of the whitespace fluff:

some.namespace.doSomething = function () {
    // ...
}(function () {
    // ...
})();

In effect, without the semicolon, the opening parenthesis that I used around the closure becomes a function call operator on the first function definition. I end up passing the second function to the first function, and then calling the result of that call as a function. If the first function returned a function as a result, I wouldn't have been getting this runtime error.

Why did I bother writing this up? Firstly, I wasted precious time due to a single missing semicolon and wanted to share the resolution.

Secondly, I'm an advocate of strict style. I always end my JavaScript lines with semicolons, even if JavaScript doesn't mandate it. In JavaScript tutorials here and there, authors sometimes preach that "semicolons in JavaScript are completely optional" and that "you don't need to use them unless you're putting multiple statements in one line." Wrong! The above piece of code is something that you're likely to see in a modern JavaScript framework (hey, closures are big!) and is therefore a non-obscure example of why you SHOULD always use semicolons.

Also, JavaScript minifiers perform better in the presence of consistent semicolon usage.


Parsing query string parameters into a collection

July 8th, 2009

A little something about the classic problem of parsing out the query parameters from a URL… There are a lot of implementations out there. Some completely lack URL-decoding, some are way too long and some are inefficient utility functions that grab values one by one. Here’s what I’ve been using in my own projects. I like it because of it’s succinctness and decoupling from document.location.search:


Turkish letter escape bookmarklet for dotSUB

June 25th, 2009

I’ve created a bookmarklet to temporarily solve a very specific problem at hand: I’m translating a TED video into Turkish, but I don’t currently have a Turkish keyboard hooked up to my computer (it’s in a box somewhere in the basement). Read the rest of this entry »


Creating Todoist items with voice using reQall

June 2nd, 2009

Todoist is an awesome, minimalistic task management service. The voice-to-web service reQall, which is a free alternative to Jott, also does a fairly good job at task management. However, I wanted to stick to Todoist and bring voice input capabilities to it. I used reQall’s e-mail forwarding along with Todoist’s HTTP API and my awesome hosting provider’s powerful features to create a quick mashup. Read the rest of this entry »


A quick and dirty XML generator in JavaScript

June 2nd, 2009

Here’s a quick XML generator (pure-string, no DOM involved) that I originally wrote for converting a jsUnity test result into JSUnit format, but which can serve a more general purpose. Read the rest of this entry »


JavaScript function definition inside a with() block: Firefox is the oddball

February 14th, 2009

I came across yet another browser discrepancy with a rather obscure scenario: A function declaration within a with block:

var obj = { a: 1 };

with (obj) {
    function foo() {
        return typeof a;
    }
}

alert(foo()); // alerts "number" on Firefox, "undefined" on others

This exposes the object properties to the function scope only on Firefox. On all other browsers that I’ve tested with (IE, Safari, Opera and Chrome), the property isn’t visible inside the function.


Browser discrepancies when calling toString() on a JavaScript function with comments

February 6th, 2009

I’ve been working on extracting some text out of a given JavaScript function when I realized that toString() may return parts of the original comments, depending on the browser. I’ve done a quick test to capture the behaviour of popular browsers. Here’s my test script:

function/*post-keyword*/fn/*post-name*/()/*post-parens*/{
    /*inside*/
}

document.write(fn.toString());

And here are the results I got on different browsers:

Browser post-keyword post-name post-parens inside
Firefox No No No No
Safari No No No No
Chrome No No Yes Yes
IE Yes Yes Yes Yes
Opera Yes Yes Yes Yes

And out of the browser context:

Engine post-keyword post-name post-parens inside
JScript Yes Yes Yes Yes
Rhino No No No No

While looking for the best solution to extract the parts that I need, I’ve implemented a workaround. Sort of. If blocking the problem can be considered a workaround:

var functionToStringHasComments = /PROBE/.test(function () {/*PROBE*/});

// ...

if (functionToStringHasComments) {
    throw "...";
}

browsersize.com updates

December 22nd, 2008

Last night I touched some code that hadn’t been touched for years. I refactored the plug-in detection code at whatsmy.browsersize.com and added detection for the Microsoft Silverlight plug-in. I also added bookmarklet support for setmy.browsersize.com and brought back to life a feature that had been broken long ago: specifying arbitrary URLs in the form http://setmy.browsersize.com/1024x768 to set the browser size. With an exclamation mark at the end, the browser gets resized and then goes back to where the the user left off: http://setmy.browsersize.com/1024×768!


Automatic Table of Contents Generation

October 19th, 2008

Here’s a JavaScript snipplet for automatically generating a table of contents based on headings in a document. It will traverse all <h1>, <h2>, <h3>, etc. elements, add anchors (<a>) to them and generate nested unordered lists (<ul>, <li>) with links to the now anchored headings. The nesting honors the hierarchy of the headings. Read the rest of this entry »


Timing Code Accurately

October 19th, 2008

The most common approach to time a function or a segment of code is to repeat it a lot of times in a loop, measure the time the entire loop takes and then divide that number with the number of iterations. Illustrating this with JavaScript (although this method applies to all languages):

var start = new Date(); // Get current time

for (var i = 0; i < n; i++) {
    myFunction();
}

var finish = new Date(): // Get current time

var ntimes = finish - start; // Elapsed time for n iterations
var once = ntimes / n; // Average time for one function call

However, this doesn't really measure just how much time n calls to myFunction took. There's also the overhead of the loop itself. What we actually end up measuring is not just the time to execute one call to myFunction but also the overhead of one iteration: Read the rest of this entry »