How to get an item from localStorage in JavaScript
Getting items from localStorage allows you to retrieve previously stored data, enabling persistent user experiences across browser sessions.
As the creator of CoreUI, a widely used open-source UI library, I’ve used localStorage retrieval extensively for restoring user themes, sidebar states, and personalized settings.
From my expertise, the localStorage.getItem()
method is the standard way to access stored data using its key.
This approach provides reliable access to persistent client-side data that maintains user preferences and application state.
Use localStorage.getItem()
to retrieve stored data by its key from browser storage.
const username = localStorage.getItem('username')
const settings = JSON.parse(localStorage.getItem('settings') || '{}')
Here localStorage.getItem('username')
retrieves the value associated with the ‘username’ key, returning null
if the key doesn’t exist. For complex data stored as JSON strings, use JSON.parse()
to convert back to objects. Always provide fallback values using the OR operator to handle missing keys gracefully.
Best Practice Note:
Always check for null values and use fallbacks since getItem() returns null for non-existent keys. This is the same approach we use in CoreUI components for robust data retrieval and graceful handling of missing user preferences.