A simple and effective one-liner:
function isMobile() { return ('ontouchstart' in document.documentElement); }
However, above code doesn't take into account the case for laptops with touchscreen.
function isMobile() {
try{ document.createEvent("TouchEvent"); return true; }
catch(e){ return false; }
}