LocalStorage Basics in JavaScript

Learn localStorage in JavaScript: setItem, getItem, removeItem, clear, keys, storing objects with JSON and checking availability. Explanation and output.

BeginnerJavaScript LocalStorage and SessionStorageExample 1 of 10

Run this in the browser console or a page script. localStorage and sessionStorage are browser features, so plain Node will not have them.

localstorage-basics.js
1// Method 1: Set item
2localStorage.setItem('username', 'John');
3localStorage.setItem('age', '30');
4localStorage.setItem('isLoggedIn', 'true');
5
6// Method 2: Get item
7const username = localStorage.getItem('username');
8console.log('Username:', username); // "John"
9
10const age = localStorage.getItem('age');
11console.log('Age:', age); // "30" (string)
12
13// Method 3: Remove item
14localStorage.removeItem('age');
15
16// Method 4: Clear all
17// localStorage.clear();
18
19// Method 5: Check if key exists
20if (localStorage.getItem('username')) {
21 console.log('Username exists');
22}
23
24// Method 6: Get all keys
25const keys = Object.keys(localStorage);
26console.log('All keys:', keys);
27
28// Method 7: Get all items
29for (let i = 0; i < localStorage.length; i++) {
30 const key = localStorage.key(i);
31 const value = localStorage.getItem(key);
32 console.log(key + ':', value);
33}
34
35// Method 8: Store object (stringify)
36const user = {
37 name: 'John',
38 age: 30,
39 email: 'john@example.com'
40};
41
42localStorage.setItem('user', JSON.stringify(user));
43
44// Retrieve object (parse)
45const storedUser = JSON.parse(localStorage.getItem('user'));
46console.log('User:', storedUser);
47
48// Method 9: Store array
49const items = ['apple', 'banana', 'orange'];
50localStorage.setItem('items', JSON.stringify(items));
51
52const storedItems = JSON.parse(localStorage.getItem('items'));
53console.log('Items:', storedItems);
54
55// Method 10: Check storage availability
56function isLocalStorageAvailable() {
57 try {
58 const test = '__localStorage_test__';
59 localStorage.setItem(test, test);
60 localStorage.removeItem(test);
61 return true;
62 } catch (e) {
63 return false;
64 }
65}
66
67if (isLocalStorageAvailable()) {
68 console.log('LocalStorage is available');
69} else {
70 console.log('LocalStorage is not available');
71}

Sample Output

All keys: ["username", "isLoggedIn"]

age is missing because removeItem deleted it before the list was made. Other keys already saved by the site may also appear.

In this one

  • How to save, read and remove localStorage items
  • Why everything comes back as a string
  • How to store objects and arrays with JSON
  • How to check that storage is available

How it works

  1. 1

    Three items are saved: username, age and isLoggedIn.

  2. 2

    username and age are read and printed.

  3. 3

    age is removed.

  4. 4

    All keys and items are listed.

  5. 5

    An object and an array are saved with JSON and read back.

  6. 6

    isLocalStorageAvailable tests storage with try/catch.

Edge cases

Saving an object without JSON

setItem('user', user) stores "[object Object]".

Always wrap objects with JSON.stringify.

Missing key

getItem('nothing') returns null.

JSON.parse(null) returns null, so check before using properties.

Storage blocked

setItem throws in some private or locked-down modes.

Wrap writes in try/catch, as Method 10 does.

What's going on

localStorage is a small key-value store built into the browser. A key is a name and a value is the data saved under it. Data stays after you close the tab and even after you restart the browser. It is kept until your code or the user clears it. That makes it good for user preferences like a dark theme, a shopping cart, saved form data, or cached data.

The main methods are simple. setItem(key, value) stores data. getItem(key) reads it back, or returns null if the key does not exist. removeItem(key) deletes one item. clear() deletes everything for this site. key(index) gives the key at a position, and length tells you how many items there are.

The most important rule: localStorage stores strings only. When you save the number 30, you get back "30". When you save true, you get back "true". Compare carefully.

Objects and arrays need JSON. JSON is a text format for data. JSON.stringify(user) turns an object into a string you can store. JSON.parse(text) turns it back into an object. If you skip stringify, you store the useless text "[object Object]".

The program also removes the age key before listing, which is why age does not appear in the key list or the loop.

Storage is domain-specific. Each website origin gets its own separate store, so one site cannot read another site's data. The limit is about 5 to 10 MB depending on the browser.

Storage can be turned off, for example in some private modes or strict settings. Method 10 tests it by writing and removing a test key inside try/catch. Best practices: check availability, handle errors, use try/catch, and validate data you read back.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does getItem return after setItem('age', 30)?

Pick an answer to check it.

Question 2

How do you store an array?

Pick an answer to check it.

Questions people ask

How long does localStorage last?

Until your code or the user clears it. It survives closing the browser.

Is localStorage safe for passwords?

No. Any script on the page can read it. Never store secrets there.

Why is the key order different in my browser?

Browsers do not promise an order for keys.