Selected topic

Local Storage

Web Apis

Prefer practical output? Use related tools below while reading.

Local storage is a way to store data locally on the client-side, allowing web applications to persist data even after the user closes their browser or navigates away from the page. This feature was introduced in HTML5 and provides an easy-to-use API for storing and retrieving key-value pairs.

Key Features:


  1. Persistent: Data is stored locally until explicitly deleted.
  2. Cross-origin: Allows data to be shared across multiple scripts running on different domains (subject to same-origin policy).
  3. IndexedDB-like interface: Local storage has a similar API to IndexedDB, but with fewer features and less flexibility.

Example Use Case:


Suppose we're building an online shopping cart application. We want to store the products added by the user in their browser's local storage so that they can be displayed even after the page is closed or reloaded.

javascript
// Add product to cart
function addToCart(product) {
    const cart = localStorage.getItem('cart');
    if (cart) {
        const existingProducts = JSON.parse(cart);
        existingProducts.push(product);
        localStorage.setItem('cart', JSON.stringify(existingProducts));
    } else {
        localStorage.setItem('cart', JSON.stringify([product]));
    }
}

// Display products in cart
function displayCart() {
const cart = localStorage.getItem('cart');
if (cart) {
const products = JSON.parse(cart);
// Render the products on the page
} else {
// Handle empty cart case
}
}


API Methods:


  1. localStorage.setItem(key, value): Stores a key-value pair in local storage.
  2. localStorage.getItem(key): Retrieves a value associated with a given key from local storage.
  3. localStorage.removeItem(key): Deletes the key-value pair with the specified key from local storage.
  4. localStorage.clear(): Removes all key-value pairs from local storage.

Note that local storage has size limitations (typically 5MB per origin), and you should be cautious when storing large amounts of data to avoid potential issues.