0
0
JavascriptHow-ToBeginner · 3 min read

How to Use localStorage in JavaScript: Simple Guide

Use localStorage.setItem(key, value) to save data, localStorage.getItem(key) to read it, and localStorage.removeItem(key) to delete it. Data saved in localStorage stays even after the browser is closed.
📐

Syntax

localStorage is a browser feature that stores data as key-value pairs in strings. Here are the main methods:

  • localStorage.setItem(key, value): Saves a value under the given key.
  • localStorage.getItem(key): Retrieves the value for the given key.
  • localStorage.removeItem(key): Deletes the key and its value.
  • localStorage.clear(): Removes all stored data.
javascript
localStorage.setItem('name', 'Alice');
const name = localStorage.getItem('name');
localStorage.removeItem('name');
localStorage.clear();
💻

Example

This example shows how to save a user's name, read it back, and then remove it from localStorage. It logs each step to the console.

javascript
localStorage.setItem('user', 'Bob');
console.log('Saved user:', localStorage.getItem('user'));
localStorage.removeItem('user');
console.log('After removal:', localStorage.getItem('user'));
Output
Saved user: Bob After removal: null
⚠️

Common Pitfalls

Common mistakes include:

  • Trying to store non-string data directly (objects must be converted to strings with JSON.stringify()).
  • Assuming data is always available (check for null when reading).
  • Using localStorage in environments where it is not supported (like some private modes).
javascript
/* Wrong way: storing object directly */
const user = { name: 'Anna' };
localStorage.setItem('user', user); // stores "[object Object]"

/* Right way: convert object to string */
localStorage.setItem('user', JSON.stringify(user));
const storedUser = JSON.parse(localStorage.getItem('user'));
console.log(storedUser.name);
Output
Anna
📊

Quick Reference

MethodDescriptionExample
setItem(key, value)Save a string value under a keylocalStorage.setItem('color', 'blue')
getItem(key)Get the string value for a keylocalStorage.getItem('color') // 'blue'
removeItem(key)Remove the key and its valuelocalStorage.removeItem('color')
clear()Remove all keys and valueslocalStorage.clear()

Key Takeaways

localStorage stores data as strings and keeps it after the browser closes.
Always convert objects to strings with JSON.stringify before saving.
Check for null when reading data to avoid errors.
Use removeItem to delete specific data and clear to remove all.
localStorage works only in the browser environment and may be disabled in private modes.