Advance JavaScript (DOM, BOM, Web API) / Web API

Client Storage - LocalStorage

🛞 Storage type

The Storage type is a built-in browser object used to store key–value (name–value) pairs.

This storage is simple, lightweight, and stores only strings.

You interact with it using methods like:

  • setItem(name, value) → store data

  • getItem(name) → read data

  • key(index) → get a key by its position

  • removeItem(name) → delete a specific item

  • clear() → delete everything

You can also check how many items are stored using:

  • length → number of stored entries

📌 If you store non-string data (like arrays/objects), it automatically converts them to strings.

📌 When you read them, you always get string data, so you usually use JSON.stringify() and JSON.parse().


🎟️ localStorage

  • localStorage is a type of Storage introduced in HTML5.

  • It saves data with no expiration time.

  • This means the data stays even after closing the browser or turning off the device.

  • Each website gets its own separate localStorage, based on:

Example:

https://example.com and http://example.com have separate storages.

You can access localStorage like this:

localStorage

It is a Storage object, so it has methods like setItem, getItem, removeItem, and properties like length.

Typing this in the console:

localStorage

gives something like:

Storage {length: 0}

1️⃣ Set a value — setItem()

localStorage.setItem('theme', 'dark');

Stores a key–value pair.

2️⃣ Check number of items — length

console.log(localStorage.length);

localStorage.length → shows how many items are stored.

3️⃣ Get a value — getItem()

localStorage.getItem('theme');

Returns the value for the key theme.

4️⃣ Remove an item — removeItem()

localStorage.removeItem('theme');

Deletes the theme entry.

5️⃣ Loop through all keys

localStorage.setItem('theme', 'light');
localStorage.setItem('backgroundColor', 'white');
localStorage.setItem('color', '#111');

let keys = Object.keys(localStorage);

for (let key of keys) {
  console.log(`${key}: ${localStorage.getItem(key)}`);
}
color: #111
theme: light
backgroundColor: white

♨️ Storing Objects

localStorage stores only strings.

To store objects → convert to string:

const settings = {
  backgroundColor: '#fff',
  color: '#111',
  theme: 'light'
};

localStorage.setItem('settings', JSON.stringify(settings));

Output stored:

'{"backgroundColor":"#fff","color":"#111","theme":"light"}'

To get it back as an object:

let storedSettings = JSON.parse(localStorage.getItem('settings'));
console.log(storedSettings);

🆚 localStorage vs cookies

🔢 No.

🧠 Feature

📦 localStorage

🍪 Cookies

1.

Storage Limit

Up to 5MB

Up to 4KB

2.

Data Sent with Requests

❌ Not sent to the server with every request

✅ Automatically sent to the server

3.

Access Control

Only accessible via JavaScript on the client

Accessible via both client-side JavaScript and server

4.

Management

Managed only by the browser (JavaScript)

Managed by both browser and server


🎫 The storage event

  • When you make a change to the Storage object, the storage event is fired on the document.

  • The storage event occurs in the following scenarios :

    • Store a name-value pair by calling the setItem() method.

    • Remove a name-value pair by calling the removeItem() method.

    • And remove all values by calling the clear() method.

  • The storage event has the following properties :

    • domain – the domain which the storage changes for.

    • newValue – the value that the key was set to or null if the key was removed.

    • oldValue – the value before the key was set or removed.

    • key – the key that was set or removed.

  • To listen for the storage event, you use the addEventListener() method of the window object like this :

addEventListener('storage', function(e){
   console.log(`The value of the ${e.key} changed for the ${e.domain}.`);
});