JS Local Storage

Introduction

LocalStorage is a type of web storage that allows JavaScript sites and apps to store and access data with no expiration date. This means the data persists even after the browser window is closed, making it useful for storing information such as shopping cart data or user login details.

Key Points

Persistence: Data stored in localStorage does not expire.

Storage Limit: LocalStorage has a higher storage limit than cookies (5MB vs. 4MB).

Security: LocalStorage is not secure for sensitive data as it can be accessed by any code running on the page.

Usage: Data stored in localStorage remains on the browser and is not sent with every HTTP request, unlike cookies.

LocalStorage Methods

LocalStorage offers several methods for interacting with the stored data. Here are the primary methods:

Method Description
setItem() Adds data to localStorage using a key-value pair.
getItem() Retrieves the value from localStorage using a key.
removeItem() Removes an item from localStorage using a key.
clear() Clears all data from localStorage.

Examples:

Add Data

To add data to localStorage, both a key and a value are required:

localStorage.setItem("city", "Pune");

Retrieve Data

To retrieve data, only the key is needed:

const res = localStorage.getItem("city");
console.log(res); // Output: Pune

Remove Data

To remove a specific item, use the key:

localStorage.removeItem("city");

Clear localStorage

To clear all data from localStorage:

localStorage.clear();

Limitations

Security: LocalStorage is not secure for storing sensitive information like usernames and passwords.

Data Protection: There is no data protection in localStorage.

Storage Limit: The maximum storage limit is 5MB.

Synchronous Nature: Operations in localStorage are synchronous, meaning each operation executes one after another.

Advantages

Persistence: Data does not expire and remains available even after closing the browser.

Ease of Use: Methods like setItem(), getItem(), removeItem(), and clear() are simple to use.

No HTTP Overhead: Unlike cookies, localStorage data is not sent with every HTTP request.

Higher Storage Limit: LocalStorage can store more data than cookies (5MB vs. 4MB).

Example:

<script>
    // Add data to localStorage
    localStorage.setItem("city", "Pune");
    localStorage.setItem("country", "India");

    // Retrieve data from localStorage
    const city = localStorage.getItem("city");
    const country = localStorage.getItem("country");

    // Display data using document.write
    document.write("<p>City: " + city + "</p>");
    document.write("<p>Country: " + country + "</p>");

    // Clear all localStorage data
    localStorage.clear();
</script>

Output:

City: Pune
Country: India