JavaScript localStorage (original) (raw)

Last Updated : 23 Jul, 2025

JavaScript localStorage is a feature that lets you store data in your browser using key-value pairs. The data stays saved even after you close the browser, so it can be used again when you open it later. This helps keep track of things like user preferences or state across different sessions.

**Syntax

ourStorage = window.localStorage;

The above will return a _storage object that can be used to access the current origin's local storage space.

Key Features of localStorage

Basic Operations with localStorage

localStorage has a simple API that allows you to interact with the browser’s local storage. The basic operations include storing, retrieving, updating, and removing items from the storage.

1. Storing Data in localStorage

To store data in localStorage, use the setItem() method. This method accepts two arguments:

**Syntax:

localStorage.setItem('key', 'value');

2. Retrieving Data from localStorage

To retrieve the data you stored, use the getItem() method. This method takes the **key as an argument and returns the associated value. If the key does not exist, it returns null.

**Syntax:

let value = localStorage.getItem('key');

3. Removing Data from localStorage

To remove a specific item from localStorage, use the removeItem() method. This method accepts the **key of the item you want to remove.

**Syntax:

localStorage.removeItem('key');

4. Clearing All Data in localStorage

If you want to clear all data stored in localStorage, use the clear() method. This will remove all key-value pairs stored in the localStorage for the current domain.

Syntax:

localStorage.clear();

5. Checking if a Key Exists in localStorage

You can check if a key exists in localStorage by using getItem(). If the key doesn’t exist, getItem() will return null.

if (localStorage.getItem('username') !== null) {
console.log('Username exists in localStorage');
} else {
console.log('Username does not exist in localStorage');
}

**Example: Using localStorage

This example demonstrates using localStorage to store, update, retrieve, and delete key/value pairs in the browser. It shows setting items, updating them, retrieving data by key, checking stored items count, and clearing the storage.

HTML `