In the case that you are trying to get a local storage item that doesn\'t exist, is it possible to set a default value for that item?
For example, let\'s say that in
If you have to use json objects, this is a clean way of doing it:
const defaultPreferences = {
darkMode: true,
language: 'es',
};
// Read, with fallback to default value
let preferences = JSON.parse(localStorage.getItem('preferences')) || defaultPreferences;
And this is how you have to save to localStorage:
preferences.language = 'fr';
// Write, always in JSON
localStorage.setItem('preferences', JSON.stringify(preferences));
Note: Remember to save to localStorage every time you modify the preferences variable, to maintain consistency.