-
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 JavaScript Web Storage API provides a modern and efficient way to store data directly in the browser. It allows web applications to save key value pairs on the client side without sending data to the server with every request. Compared to cookies, Web Storage is faster, simpler, and capable of storing much larger amounts of data. It is widely used for saving user preferences, application state, and temporary data.
In this tutorial, you will learn what the JavaScript Web Storage API is, how it works, its types, methods, practical examples, common mistakes, best practices, and real world use cases.
The Web Storage API is a browser feature that allows websites to store data as key value pairs. This data remains available even after page refreshes, depending on the storage type used.
The Web Storage API includes two main objects:
localStorage
sessionStorage
Both objects work in a similar way, but they differ in how long the data is stored.
The Web Storage API is important because it allows developers to:
Store data without server interaction
Save user preferences like theme or language
Improve performance by reducing server requests
Maintain application state
Build offline friendly applications
Replace many cookie based use cases
Modern web applications rely heavily on Web Storage for smooth and fast user experiences.
The localStorage object stores data without an expiration time. The data remains available even after the browser is closed and reopened.
localStorage.setItem("username", "Amit");
This stores the data permanently unless manually removed.
let name = localStorage.getItem("username");
console.log(name);
If the key does not exist, it returns null.
localStorage.setItem("username", "Suman");
The value is overwritten with the new one.
localStorage.removeItem("username");
localStorage.clear();
This removes all stored keys for the website.
The sessionStorage object stores data only for the duration of the browser session. Once the tab or browser is closed, the data is removed automatically.
sessionStorage.setItem("city", "Delhi");
let city = sessionStorage.getItem("city");
console.log(city);
sessionStorage.removeItem("city");
sessionStorage.clear();
Session storage is useful for temporary data that should not persist.
Understanding the difference helps choose the right option.
localStorage persists until manually cleared
sessionStorage is cleared when the tab closes
Both store data as strings
Both have similar methods
Both are limited to the same origin
Choosing correctly avoids unexpected data loss or persistence.
Web Storage stores only strings. To store objects or arrays, you need to convert them to JSON.
let user = {
name: "Ravi",
age: 28,
role: "Developer"
};
localStorage.setItem("userData", JSON.stringify(user));
let data = localStorage.getItem("userData");
let userObject = JSON.parse(data);
console.log(userObject.name);
This approach is very common in real applications.
function setTheme(theme) {
localStorage.setItem("theme", theme);
}
let savedTheme = localStorage.getItem("theme");
if (savedTheme) {
document.body.className = savedTheme;
}
This improves user experience by remembering preferences.
sessionStorage.setItem("email", "rahul@example.com");
This is useful when users accidentally refresh the page.
let cartItems = ["Book", "Laptop", "Pen"];
localStorage.setItem("cart", JSON.stringify(cartItems));
let cart = JSON.parse(localStorage.getItem("cart"));
console.log(cart);
This avoids losing cart data on refresh.
Web Storage allows much more data than cookies.
Around 5 to 10 MB per origin
Much larger than cookies
Data is stored per domain
Data is not sent with HTTP requests
These limits make Web Storage efficient and scalable.
Forgetting that values are stored as strings
Not using JSON for objects and arrays
Storing sensitive data like passwords
Clearing storage unintentionally
Assuming storage is shared across domains
Avoiding these mistakes improves reliability and security.
Use localStorage for long term data
Use sessionStorage for temporary data
Always validate stored data
Remove unused keys
Avoid storing sensitive information
Use meaningful key names
Following these practices keeps applications clean and secure.
Understanding the difference is important.
Web Storage is client side only
Cookies are sent to the server
Web Storage supports larger data
Cookies support expiration and security flags
Web Storage is better for performance, while cookies are better for authentication.
The Web Storage API is widely used in:
Theme and language settings
Authentication state storage
Shopping carts
Offline web applications
Form auto save features
User onboarding progress
Most modern single page applications depend on Web Storage.
When using Web Storage:
Do not store passwords or tokens
Protect against XSS attacks
Validate data before use
Clear storage on logout
Security is critical because Web Storage is accessible through JavaScript.
The Web Storage API is supported by all modern browsers, including Chrome, Firefox, Edge, Safari, and mobile browsers. This makes it a reliable choice for production applications.
The JavaScript Web Storage API provides a simple, fast, and efficient way to store data in the browser. With localStorage for persistent data and sessionStorage for temporary data, developers can manage application state, improve performance, and enhance user experience. By understanding how to store, retrieve, update, and remove data, and by following best practices, you can use Web Storage effectively in real world JavaScript 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
