JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript Web Storage API


The Web Storage API is a modern way to store data directly in the browser. Unlike cookies, it allows storing larger amounts of data without sending it to the server on every request.

Web storage is part of the Browser Object Model (BOM) and includes two main types:

  1. localStorage – stores data permanently until manually cleared

  2. sessionStorage – stores data for the current session (cleared when the browser tab is closed)

1. Why Use Web Storage?

Web storage is useful for:

  • Saving user preferences (theme, language)

  • Storing temporary data (like shopping cart items)

  • Avoiding repeated server requests

  • Creating offline-capable web applications

Advantages over cookies:

Feature Cookies Web Storage
Data size limit ~4KB ~5–10MB
Sent with HTTP request Yes No
Lifetime Manual/Expires sessionStorage (tab) / localStorage (permanent)
Easier API No Yes

2. localStorage – Permanent Storage

localStorage stores key-value pairs permanently (even after closing the browser).

Example: Saving Data

// Save username in localStorage
localStorage.setItem("username", "Vicky");

// Save preferred theme
localStorage.setItem("theme", "dark");

Example: Reading Data

// Read data from localStorage
let user = localStorage.getItem("username");
console.log("Username:", user);

// If a key does not exist, it returns null
let language = localStorage.getItem("language"); // null

Example: Removing Data

// Remove a single item
localStorage.removeItem("theme");

// Clear all data
localStorage.clear();

3. sessionStorage – Temporary Storage

sessionStorage stores data only for the current tab. Once the tab is closed, data is removed.

Example:

// Save data in sessionStorage
sessionStorage.setItem("sessionName", "VickySession");

// Read data
console.log("Session Name:", sessionStorage.getItem("sessionName"));

// Remove a single item
sessionStorage.removeItem("sessionName");

// Clear all session data
sessionStorage.clear();

Use case: temporary data like form progress, one-time alerts, or session-specific preferences.

4. Practical Example: Remember User Name with localStorage

<input type="text" id="nameInput" placeholder="Enter your name">
<button onclick="saveName()">Save Name</button>
<button onclick="showName()">Show Name</button>

<script>
function saveName() {
    let name = document.getElementById("nameInput").value;
    if(name != "") {
        // Save the name permanently
        localStorage.setItem("username", name);
        alert("Name saved!");
    }
}

function showName() {
    let name = localStorage.getItem("username");
    if(name) {
        alert("Welcome back, " + name + "!");
    } else {
        alert("No name found.");
    }
}
</script>

Explanation:

  • User enters a name and it’s saved in localStorage.

  • Name persists even if the browser is closed and reopened.

5. Practical Example: Shopping Cart with sessionStorage

<button onclick="addItem('Laptop')">Add Laptop</button>
<button onclick="addItem('Mouse')">Add Mouse</button>
<button onclick="showCart()">Show Cart</button>

<script>
function addItem(item) {
    let cart = JSON.parse(sessionStorage.getItem("cart")) || [];
    cart.push(item);
    sessionStorage.setItem("cart", JSON.stringify(cart));
    alert(item + " added to cart!");
}

function showCart() {
    let cart = JSON.parse(sessionStorage.getItem("cart")) || [];
    alert("Your Cart: " + cart.join(", "));
}
</script>

Explanation:

  • Cart items are stored in sessionStorage.

  • Data is temporary and will disappear when the tab is closed.

  • JSON.stringify and JSON.parse are used for storing arrays.

6. Removing Items and Clearing Storage

// Remove specific key
localStorage.removeItem("username");

// Clear all data
localStorage.clear();

// For sessionStorage
sessionStorage.removeItem("cart");
sessionStorage.clear();

Tip: Always remove or clear unnecessary data to avoid clutter.

7. Checking Support for Web Storage

Not all older browsers support Web Storage. You can check with:

if(typeof(Storage) !== "undefined") {
    console.log("Web Storage supported");
} else {
    console.log("Web Storage not supported");
}

Explanation:

  • typeof(Storage) checks if localStorage and sessionStorage are available.

  • Always good to include this check for fallback handling.

8. Best Practices

  1. Store small data – do not exceed storage limits (usually 5–10MB).

  2. Use JSON – for arrays or objects, always stringify before saving and parse when reading.

  3. Secure sensitive data – avoid storing passwords or confidential info in Web Storage.

  4. Use sessionStorage for temporary data – like one-time notifications or in-progress forms.

  5. Clear unused data – helps prevent performance issues and clutter.

Summary of the Tutorial

The Web Storage API allows you to store and manage data in the browser efficiently:

  • localStorage – permanent storage for user preferences or persistent data

  • sessionStorage – temporary storage for session-specific data

  • setItem() / getItem() / removeItem() / clear() – main methods to manipulate storage

Advantages over cookies: larger capacity, no server overhead, simpler API.

Mastering Web Storage is essential for creating dynamic, interactive, and offline-capable web applications.


Practice Questions

  1. How can you save a username in localStorage and display it later on the page?

  2. Write a function to save a user’s theme preference (dark/light) in localStorage and apply it when the page loads.

  3. How can you store a shopping cart array in sessionStorage and retrieve it later?

  4. Create a program to remove a specific key from localStorage when a button is clicked.

  5. How can you clear all data from sessionStorage at once?

  6. Write a program that checks if the browser supports Web Storage before saving any data.

  7. How can you update an existing localStorage value without overwriting other data?

  8. Create a function that saves a form’s input fields in sessionStorage so that they remain filled if the user accidentally refreshes the page.

  9. How can you store multiple objects in localStorage using JSON?

  10. Write a program that counts page visits using localStorage and displays the number to the user.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top