Uncaught TypeError: Cannot read property '1' of null in webOS

I've been debugging the Kwwika JavaScript library in webOS today following seeing this obscure error:

Uncaught TypeError: Cannot read property '1' of null

After debugging using the very cool browser IDE Palm Ares I got the bottom of it. This happens when you are trying to access a property, or Array index, via square brackets. If it were a named member variable, e.g. something["foobar"], it would be more easy to track down but because it's something[1] it makes the difficult to interpret, especially given the exception message.

Within Palm webOS an application is served from a file path. Clearly this means there is not being served from a web server over HTTP protocol. Here's an example where the following would work in a web browser but not in webOS and it also highlights the reason for my exception.

var url = document.location.href;
var match = url.match(/^(https?)/)[1];

In a webOS application this throws an exception because neither "http" or "https" can be matched and then we are trying to get the segment at index 1. Effectively we are calling "null[1]". When running an application in webOS the value of document.location.href is generally something like:

file:///media/cryptofs/apps/usr/palm/applications/com.mycompany.sampleapp/index.

i.e. the file protocol.

So, one good way of tracking down this particular error is to search for "[1]" within your codebase. Maybe the code was being a bit naughty and should have been checking the match first.