Persistent variables

by Kai Chan

JavaScript

//    getter function of 'persistent' variables.
function getPersistent(myVar) {
    //    ensure the localStorage object exists.
    //    return the variable we are looking for if it does or: undefined.
    return (window.localStorage)? localStorage.getItem(myVar) : undefined;
}

//    setter function of 'persistent' variables.
function setPersistent(myVar, value) {
    //    ensure the localStorage object exists.
    if (window.localStorage) {
        //    set the variable.
        localStorage.setItem(myVar, value);
    }
}

//    first run (page refresh) returns undefined.
//    second run returns 4.
console.log(getPersistent('test'));

//    we set the localStorage var 'test' to '4'.
//    note that localStorage only saves strings.
//    so you need to parse/convert the data if you want to modify.
console.log(setPersistent('test', '4'));

//    returns localStorage var 'test' ==> 4.
console.log(getPersistent('test'));