Check if localStorage is available

Use modernizr's approach (you might want to change my function name to something better):

function lsTest(){
    var test = 'test';
    try {
        localStorage.setItem(test, test);
        localStorage.removeItem(test);
        return true;
    } catch(e) {
        return false;
    }
}

if(lsTest() === true){
    // available
}else{
    // unavailable
}

It's not as concise as other methods but that's because it's designed to maximise compatibility.

The original source: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js

Working example: http://jsfiddle.net/6sm54/2/


I'd check that localStorage is defined prior to any action that depends on it:

if (typeof localStorage !== 'undefined') {
    var x = localStorage.getItem('mod');
} else {
    // localStorage not defined
}

UPDATE:

If you need to validate that the feature is there and that it is also not turned off, you have to use a safer approach. To be perfectly safe:

if (typeof localStorage !== 'undefined') {
    try {
        localStorage.setItem('feature_test', 'yes');
        if (localStorage.getItem('feature_test') === 'yes') {
            localStorage.removeItem('feature_test');
            // localStorage is enabled
        } else {
            // localStorage is disabled
        }
    } catch(e) {
        // localStorage is disabled
    }
} else {
    // localStorage is not available
}