-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
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 Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
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:
localStorage – stores data permanently until manually cleared
sessionStorage – stores data for the current session (cleared when the browser tab is closed)
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 |
localStorage
stores key-value pairs permanently (even after closing the browser).
// Save username in localStorage
localStorage.setItem("username", "Vicky");
// Save preferred theme
localStorage.setItem("theme", "dark");
// 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
// Remove a single item
localStorage.removeItem("theme");
// Clear all data
localStorage.clear();
sessionStorage
stores data only for the current tab. Once the tab is closed, data is removed.
// 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.
<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.
<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.
// 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.
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.
Store small data – do not exceed storage limits (usually 5–10MB).
Use JSON – for arrays or objects, always stringify before saving and parse when reading.
Secure sensitive data – avoid storing passwords or confidential info in Web Storage.
Use sessionStorage for temporary data – like one-time notifications or in-progress forms.
Clear unused data – helps prevent performance issues and clutter.
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.
How can you save a username in localStorage and display it later on the page?
Write a function to save a user’s theme preference (dark/light) in localStorage and apply it when the page loads.
How can you store a shopping cart array in sessionStorage and retrieve it later?
Create a program to remove a specific key from localStorage when a button is clicked.
How can you clear all data from sessionStorage at once?
Write a program that checks if the browser supports Web Storage before saving any data.
How can you update an existing localStorage value without overwriting other data?
Create a function that saves a form’s input fields in sessionStorage so that they remain filled if the user accidentally refreshes the page.
How can you store multiple objects in localStorage using JSON?
Write a program that counts page visits using localStorage and displays the number to the user.
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 Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts