It does the job, but it feels ugly and repetitive. Any way to improve it? Also, is it considered good practice to use a try catch like this to check if a value is valid?
function readJson(key, fallback) {
localStorage.getItem(key) ??
localStorage.setItem(key, fallback);
try {
return JSON.parse(localStorage.getItem(key));
} catch {
localStorage.setItem(key, fallback);
return JSON.parse(localStorage.getItem(key));
}
}
try {
// using hex2Rgb only to check if localStorage.getItem(hexColor) has valid value
hex2Rgb(localStorage.getItem(hexColor));
setColor(localStorage.getItem(hexColor));
} catch {
setColor("#000000");
}