Brad Brad - 6 days ago 5
Javascript Question

Cleaner way to write this code

I have the following code which works perfectly, but I'm calling the

getItem
function twice, which seems unnecessary. How can I tidy it up?

if(localStorage.getItem("preferences") == null {
//show set preferences page
} else {
var preferences = localStorage.getItem("preferences");
//do stuff
}

Answer

Just do the getItem once:

var preferences = localStorage.getItem("preferences");
if (preferences == null) {
    //show set preferences page
} else {
    //do stuff
}

And unless it's valid that preferences could be a falsy value other than null, I'd probably invert those blocks:

var preferences = localStorage.getItem("preferences");
if (preferences) {
    //do stuff
} else {
    //show set preferences page
}