Thanks to visit codestin.com
Credit goes to coreui.io

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.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to loop inside React JSX
How to loop inside React JSX

The Best Bootstrap Alternative for Developers in 2025
The Best Bootstrap Alternative for Developers in 2025

How to Migrate from create-react-app to Vite?
How to Migrate from create-react-app to Vite?

How to loop through a 2D array in JavaScript
How to loop through a 2D array in JavaScript

Answers by CoreUI Core Team