Featured Article

JS LocalStorage Example: Save Data Locally with This Simple Tutorial

Adam Jul 13, 2026

LocalStorage is a web storage API that allows data to be stored locally in web browsers with no expiration time. Unlike sessionStorage, which resets when the page session ends, LocalStorage persists even after the browser is closed and reopened. This makes it an excellent choice when you want to store user-specific settings or data that should persist across multiple sessions.

JavaScript Local Storage: Store Data That Lasts πŸ’ΎπŸš€
JavaScript Local Storage: Store Data That Lasts πŸ’ΎπŸš€

In this article, we'll explore an example of how to use LocalStorage in JavaScript, so you can better understand how to implement it in your own applications. We'll cover the basics of using LocalStorage, then dive into two practical use cases: storing user preferences and saving high scores in a simple game.

Local Storage
Local Storage

Getting Started with LocalStorage

Before we dive into the examples, let's first understand the basic syntax of using LocalStorage in JavaScript.

Cookies vs Local Storage in JavaScript
Cookies vs Local Storage in JavaScript

To store data in LocalStorage, you use the setItem() method. The method takes two arguments: a key (a string) and a value (which can be a string or an object). Here's an example of storing a user's name:

```javascript localStorage.setItem('userName', 'John Doe'); ```

To retrieve the data, use the getItem() method, passing in the key:

To Do App With Local Storage | Step By Step Javascript Project
To Do App With Local Storage | Step By Step Javascript Project

```javascript const userName = localStorage.getItem('userName'); console.log(userName); // Outputs: John Doe ```

And to remove an item, use the removeItem() method:

```javascript localStorage.removeItem('userName'); ```

Storing User Preferences

One common use case for LocalStorage is storing user preferences. For example, a user might choose their preferred language or theme for your website.

JavaScript Session Storage: Temporary Data Storage Made Easy πŸ’ΎπŸš€
JavaScript Session Storage: Temporary Data Storage Made Easy πŸ’ΎπŸš€

Let's create a simple example that stores a user's chosen theme (light or dark):

```javascript function setTheme(theme) { localStorage.setItem('theme', theme); // Update the UI based on the chosen theme document.body.classList.toggle('dark', theme === 'dark'); } function getStoredTheme() { const storedTheme = localStorage.getItem('theme'); if (storedTheme) { setTheme(storedTheme); } else { // If no theme is stored, default to light setTheme('light'); } } // Call getStoredTheme to load the user's chosen theme when the page loads getStoredTheme(); ```

Saving High Scores in a Simple Game

Another great use case for LocalStorage is saving game data. Let's create a simple high score list for a game, using an array of objects to store each player's name and score:

React Native Get Save Value Locally using AsyncStorage in App Memory Example
React Native Get Save Value Locally using AsyncStorage in App Memory Example

```javascript let highScores = JSON.parse(localStorage.getItem('highScores')) || []; function saveHighScore(playerName, score) { const newScore = { name: playerName, score, }; highScores.push(newScore); highScores.sort((a, b) => b.score - a.score); highScores = highScores.slice(0, 5); // Keep only the top 5 scores localStorage.setItem('highScores', JSON.stringify(highScores)); } // Usage saveHighScore('Alice', 1500); ```

Handling LocalStorage Limitations

While LocalStorage is a powerful tool, it's important to be aware of its limitations. Each browser implements a max storage limit, which is typically around 5-10MB. If your site tries to store more data than the limit, it will throw a QUOTA_EXCEEDED_ERROR.

What is localStorage used for?
What is localStorage used for?
Web Storage
Web Storage
Web Storage: Cookies vs Local Storage vs Session Storage
Web Storage: Cookies vs Local Storage vs Session Storage
a diagram showing the different types of an invertor and dynatic inventory system
a diagram showing the different types of an invertor and dynatic inventory system
⚑ Next.js Cheatsheet Every Beginner Needs in 2026

⚑ Want to build faster React apps? This Next.js cheatsheet gives you everything you need to start building today.
What You'll Learn:
πŸ”Ή Setup in 3 commands
πŸ”Ή Image optimization that cuts file size by 70%
πŸ”Ή Routing that loads 40% faster
πŸ”Ή API routes in 4 lines of code
πŸ”Ή Deploy in 60 seconds

Perfect For:
βœ… React developers learning Next.js
βœ… Beginners starting web development
βœ… Anyone building modern web apps
Swipe through all 10 slides ➑️ Save... Frontend Developer, Educational Software, Site Words, Innovation Strategy, Educational Websites, Digital Marketing Company, Skills To Learn, Digital Marketing Services, Digital Marketing Strategy
⚑ Next.js Cheatsheet Every Beginner Needs in 2026 ⚑ Want to build faster React apps? This Next.js cheatsheet gives you everything you need to start building today. What You'll Learn: πŸ”Ή Setup in 3 commands πŸ”Ή Image optimization that cuts file size by 70% πŸ”Ή Routing that loads 40% faster πŸ”Ή API routes in 4 lines of code πŸ”Ή Deploy in 60 seconds Perfect For: βœ… React developers learning Next.js βœ… Beginners starting web development βœ… Anyone building modern web apps Swipe through all 10 slides ➑️ Save... Frontend Developer, Educational Software, Site Words, Innovation Strategy, Educational Websites, Digital Marketing Company, Skills To Learn, Digital Marketing Services, Digital Marketing Strategy
Node.js Express Login example with MySQL database
Node.js Express Login example with MySQL database
10+ Top Node.js Frameworks for Building Scalable Web Applications
10+ Top Node.js Frameworks for Building Scalable Web Applications
Logging in Node.js the Right Way
Logging in Node.js the Right Way
the inside of a storage room with shelves and shelvings in an enclosed area
the inside of a storage room with shelves and shelvings in an enclosed area
Top 24 Small Storage Room Ideas
Top 24 Small Storage Room Ideas
Node.js SDK Checklist
Node.js SDK Checklist
Book Management Information System in Vue.JS
Book Management Information System in Vue.JS
25 Node Js Best Practices to Build Exceptional Applications
25 Node Js Best Practices to Build Exceptional Applications
Why Agencies Trust Node.js for Scalable Applications
Why Agencies Trust Node.js for Scalable Applications
the storage room is filled with various items
the storage room is filled with various items
a computer screen with the text underlined list - up
a computer screen with the text underlined list - up
an info poster showing how to start a self storage facility
an info poster showing how to start a self storage facility
Self Storage Units and Facilities | U-Haul
Self Storage Units and Facilities | U-Haul
a poster showing different types of storage items
a poster showing different types of storage items
Smart Business Storage Tips for 2025
Smart Business Storage Tips for 2025

To handle this, you can periodically clear out old or unnecessary data, or compress data before storing it. It's also a good idea to check for this error and provide meaningful user feedback if it occurs:

```javascript try { localStorage.setItem('newItem', 'new value'); } catch (error) { if (error.name === 'QUOTA_EXCEEDED_ERROR') { console.log('Storage limit exceeded. Clearing old data...'); // Clear old data or ask the user to clear some data } else { throw error; // Rethrow any other errors } } ```

LocalStorage is a powerful tool that can significantly enhance the user experience by persisting data across sessions. By understanding how to use it effectively and responsibly, you can create more engaging and personalized web applications.

Now that you've seen how to use LocalStorage in these examples, it's your turn to apply this knowledge in your own projects. Keep exploring and expanding your skills to make the most out of this essential web API.