Storage
In JavaScript, storage refers to mechanisms that allow data to be saved in the user’s browser so that it can persist across page reloads or even sessions. JavaScript provides several ways to store data, each with different storage capacities and scopes
Types of JavaScript Storage
There are three main types of storage in JavaScript:
1. Local Storage
2. Session Storage
3. Cookies
Difference | Local Storage | Session Storage | Cookies |
---|---|---|---|
Persistence | Data stored in localStorage persists even after the browser is closed and reopened. The data does not expire unless explicitly deleted. | Data stored in sessionStorage is only available for the duration of the page session (until the tab or browser is closed). | Cookies can have an expiration date or be session-based. If no expiration is set, they are deleted when the browser is closed. |
Capacity | Typically, around 5MB per origin (per domain). | Typically, around 5MB per origin (per domain). | Very limited (usually around 4KB per cookie). |
Scope | Data is accessible across different pages of the same domain but not across different domains or tabs. | Data is available only within the same tab, so it won’t be shared across tabs or windows. | Cookies are sent with every HTTP request made to the domain (server-side access as well as client-side access). |
Let's look at each one in detail.
1. Local Storage: Storing Data Forever
Local Storage is like a special box in your web browser that can hold things long, even after you close the website or turn off your computer. The data stays there until you or the website decides to delete it.
For Example:
Think about a game that saves you a high score on your computer. When you open the game again, it shows your high score because the score is stored in Local Storage.
How do we use it?
We can use Local Storage with simple commands in JavaScript.
<body>
<script>
// Saving data
localStorage.setItem(‘name’, ‘Saad’); // This saves ‘Saad’ under the key ‘name’
// Retrieving data
let name = localStorage.getItem(‘name’); // This gets the value ‘Saad’
document.write(“Username:”, name)
// Removing data
localStorage.removeItem(‘name’); // This deletes the ‘name’ data
</script>
</body>
Code Explanation:
1. Saving Data:
localStorage.setItem(‘name’, ‘Saad’);
localStorage.setItem(‘name’, ‘Saad’) stores a piece of data in the browser’s localStorage.
It stores ‘Saad’ under the key ‘name’.
This data persists even if the browser or tab is closed and reopened.
2. Retrieving Data:
let name = localStorage.getItem(‘name’);
localStorage.getItem(‘name’) retrieves the value associated with the key ‘name’.
In this case, it will return ‘Saad’ as that was the value stored earlier.
The value is stored in the variable name.
3. Displaying Data:
document.write(“Username:”, name);
document.write() is used to display the text “Username: Saad” in the web page, where name holds the value ‘Saad’.
This will render the text directly on the page.
4. Removing Data:
localStorage.removeItem(‘name’);
localStorage.removeItem(‘name’) deletes the data stored under the key ‘name’ in localStorage.
After this line runs, if you try to retrieve ‘name’ again using localStorage.getItem(‘name’), it will return null because the data has been removed.
• The code first stores a name (‘Saad’) in the localStorage.
• Then it retrieves the value associated with the key ‘name’ and displays it on the web page.
• Finally, it removes the data stored under the ‘name’ key from localStorage.
This example demonstrates how to store, retrieve, and delete data using localStorage in JavaScript.
Output:
2. Session Storage: Temporary Storage
Session Storage is like a temporary box. It keeps information only as long as the tab (or window) is open. Once you close the tab or window, everything in Session Storage disappears.
For Example:
Imagine you’re filling out a form on a website. If the page accidentally refreshes or crashes, you don’t want to lose what you typed. Session Storage can temporarily store that information so you don’t lose it while you’re still on the same page.
How do we use it?
<body>
<script>
// Saving data
sessionStorage.setItem(‘score’, ’50’); // Save ’50’ under ‘score’
// Retrieving data
let score = sessionStorage.getItem(‘score’); // Gets the score
document.write(“Score : “,score);
// Removing data
sessionStorage.removeItem(‘score’); // Deletes the ‘score’ data
</script>
</body>
Code Explanation:
1. Saving Data:
sessionStorage.setItem(‘score’, ’50’);
sessionStorage.setItem(‘score’, ’50’) stores a value in the sessionStorage.
The key is ‘score’, and its value is ’50’.
SessionStorage stores data only for the duration of the page session. The data will be lost when the page is closed or reloaded.
2. Retrieving Data:
let score = sessionStorage.getItem(‘score’);
sessionStorage.getItem(‘score’) retrieves the value associated with the key ‘score’ from sessionStorage.
In this case, it will return ’50’, which was stored earlier.
The value is then stored in the variable score.
3. Displaying Data:
document.write(“Score : “, score);
document.write() is used to display the text “Score : 50” on the webpage.
The value of the score, which is ’50’, is written to the document.
4. Removing Data:
sessionStorage.removeItem(‘score’);
sessionStorage.removeItem(‘score’) deletes the data stored under the key ‘score‘ in sessionStorage.
After this line, if you try to retrieve ‘score’ again using sessionStorage.getItem(‘score’), it will return null since the data has been removed.
Output:
• The code first stores a score value (’50’) in sessionStorage.
• Then it retrieves the value associated with the ‘score’ key and displays it on the webpage.
• Finally, it removes the ‘score’ data from sessionStorage, so the data won’t persist across page refreshes or after the session ends.
This example demonstrates how to store, retrieve, and delete data using sessionStorage in JavaScript, with the data only lasting for the duration of the page session.
3. Cookies: Tiny Bits of Information
Cookies are small pieces of data that websites use to remember information about you. Cookies are sent to the server each time you visit the site, which helps the site remember things like your language preference or if you’re logged in.
For Example:
A website might use a cookie to remember that you’re logged in. Every time you visit, the website checks the cookie and logs you in automatically.
How do we use it?
<body>
<script>
document.cookie = “user=Saad; expires=Thu, 18 Dec 2025 12:00:00 UTC”;
let userCookie = document.cookie.split(‘; ‘).find(row => row.startsWith(‘user=’)).split(‘=’)[1];
document.write(“User Cookie : “, userCookie);
// Displays the value of the ‘user’ cookie
document.cookie = “user=; expires=Thu, 01 Jan 1970 00:00:00 UTC”;
</script>
</body>
Code Explanation:
1. Creating a Cookie:
document.cookie = “user=Saad; expires=Thu, 18 Dec 2025 12:00:00 UTC”;
This line creates a cookie named ‘user’ and assigns it the value ‘Saad’.
expires=Thu, 18 Dec 2025 12:00:00 UTC sets the expiration date of the cookie. The cookie will persist until December 18, 2025. If no expiration date is set, the cookie will only last for the current session (until the browser is closed).
2. Reading Cookies:
let userCookie = document.cookie.split(‘; ‘).find(row => row.startsWith(‘user=’)).split(‘=’)[1]; document.write(“User Cookie : “, userCookie); // Displays the value of the ‘user’ cookie
document.cookie returns all cookies in the form of a string, where each cookie is separated by a semicolon (;).
.split(‘; ‘) splits the string into individual cookies.
.find(row => row.startsWith(‘user=’)) finds the cookie that starts with ‘user=’.
.split(‘=’)[1] extracts the value of the ‘user’ cookie (which is ‘Sada’).
The document.write() method then displays the value of the ‘user’ cookie on the webpage.
3. Deleting a Cookie:
document.cookie = “user=; expires=Thu, 01 Jan 1970 00:00:00 UTC”;
To delete a cookie, you set its value to an empty string and set its expires date to a past date (January 1, 1970).
This ensures that the cookie is expired and removed from the browser.
The ‘user’ cookie will be deleted, and if you try to access it again, it will no longer exist.
• The code first creates a cookie named ‘user’ with the value ‘Saad’ and an expiration date of December 18, 2025.
• It then reads the cookie value using document.cookie, extracting the ‘user’ cookie and displaying it on the page.
• Finally, it deletes the ‘user’ cookie by setting its value to an empty string and giving it an expiration date in the past.
This example demonstrates how to create, read, and delete cookies using JavaScript.
Output:
Types of JavaScript Storage
• Security: Be careful about what data you store in JavaScript storage. Sensitive information like passwords should never be saved in Local Storage or Session Storage, as they are easily accessible.
• Storage Limits: While Local Storage and Session Storage can hold a lot of data (around 5MB), cookies are much smaller (only about 4KB).
• Cross-tab Communication: Local Storage and Session Storage are limited to a single tab or window, meaning data from one tab isn’t automatically shared with others. However, Local Storage can be accessed across tabs in the same browser.
Practice Scenarios
1. What is localStorage and how is it used?
Objective:
• Understand the concept of persistent client-side storage.
• Learn how to use localStorage to store data that persists across browser sessions.
• Understand how to store simple key-value pairs and retrieve them.
Task:
• Store a user’s name in localStorage when a button is clicked.
• Retrieve the name from localStorage and display it on page load.
Here’s an example program:
<body>
<input type=”text” id=”username” placeholder=”Enter your name”>
<button onclick=”saveName()”>Save Name</button>
<p id=”greeting”></p>
<script>
function saveName() {
const name = document.getElementById(“username”).value;
localStorage.setItem(“username”, name); // Store the name in localStorage
}
window.onload = function() {
const storedName = localStorage.getItem(“username”);
if (storedName) {
document.getElementById(“greeting”).textContent = `Hello, ${storedName}!`;
}
}
</script>
</body>
Output:
2. How can you remove an item from localStorage?
Objective:
• Learn how to remove specific items from localStorage.
• Understand how removing items can be useful for clearing out data that is no longer needed.
Task:
• Create a button that removes a stored item from localStorage and refreshes the page to show that the data is gone.
Here’s an example program:
<body>
<button onclick=”removeItem()”>Remove Stored Item</button>
<script>
// Store a value in localStorage
localStorage.setItem(“user”, “John”);
function removeItem() {
localStorage.removeItem(“user”); // Remove specific item
alert(“Item removed!”);
location.reload(); // Reload the page to reflect changes
}
</script>
</body>
Output:
Before Click:
After:
3. What is sessionStorage and how does it differ from localStorage?
Objective:
• Understand the difference between localStorage and sessionStorage.
• Learn that sessionStorage stores data only for the duration of the page session (until the browser tab is closed).
• Experiment with storing, retrieving, and clearing data from sessionStorage.
Task:
• Store a user’s input in sessionStorage and display it on page load.
• Observe how the data disappears when the tab is closed.
Here’s an example program:
<body>
<input type=”text” id=”sessionItem” placeholder=”Enter session item”>
<button onclick=”saveSessionItem()”>Save Session Item</button>
<p id=”sessionMessage”></p>
<script>
function saveSessionItem() {
const item = document.getElementById(“sessionItem”).value;
sessionStorage.setItem(“sessionItem”, item); // Store data in sessionStorage
}
window.onload = function() {
const savedItem = sessionStorage.getItem(“sessionItem”);
if (savedItem) {
document.getElementById(“sessionMessage”).textContent = `Session Item: ${savedItem}`;
} else {
document.getElementById(“sessionMessage”).textContent = “No item stored.”;
}
}
</script>
</body>
Output:
Before storing:
After:
4. How do you clear all data stored in sessionStorage?
Objective:
• Learn how to clear all items stored in sessionStorage.
• Understand how clear() works to remove all key-value pairs from both storages.
Task:
• Write a script to clear all data from sessionStorage when a button is clicked.
• Explain the difference in behavior between clear() for sessionStorage.
Here’s an example program:
<body>
<button onclick=”clearStorage()”>Clear Storage</button>
<script>
// Storing values in sessionStorage
sessionStorage.setItem(“Name”, “Saad”);
function clearStorage() {
sessionStorage.clear(); // Clear all items in sessionStorage
alert(“Storage cleared!”);
}
</script>
</body>
Output:
Before Click:
After:
5. How do you check if a specific cookie exists?
Objective:
• Learn how to check if a specific cookie is set in the browser.
• Understand the method of parsing document.cookie to find a cookie by name.
Task:
• Check if a cookie named username exists and display a message based on its existence.
Here’s an example program:
<body>
<button onclick=”checkCookie()”>Check if Cookie Exists</button>
<p id=”cookieStatus”></p>
<script>
function checkCookie() {
const cookie = document.cookie.split(“; “).find(row => row.startsWith(“username=”));
if (cookie) {
document.getElementById(“cookieStatus”).textContent = “Cookie exists!”;
} else {
document.getElementById(“cookieStatus”).textContent = “Cookie does not exist!”;
}
}
Output:
Before Click:
After:
6. How do you update the value of a cookie?
Objective:
• Learn how to update the value of an existing cookie.
• Understand that to update a cookie, you must overwrite it by setting a new value and expiration date.
Task:
• Create a script that updates the value of a username cookie.
Here’s an example program:
<body>
<button onclick=”updateCookie()”>Update Cookie</button>
<p id=”cookieValue”></p>
<script>
// Set a cookie if it doesn’t already exist
if (!document.cookie.includes(“username”)) {
document.cookie = “username=Saad; expires=Thu, 18 Dec 2025 12:00:00 UTC; path=/”;
}
function updateCookie() {
document.cookie = “username=Amir; expires=Thu, 18 Dec 2025 12:00:00 UTC; path=/”; // Update the cookie
document.getElementById(“cookieValue”).textContent = “Cookie updated!”;
}
</script>
</body>
Output:
Before Click:
After:
Course Video
YouTube Reference :
JavaScript storage refers to mechanisms like Local Storage, Session Storage, and Cookies, which allow you to store data on a user’s browser for use across sessions or pages. Learn more in our JavaScript storage free course video.
- Local Storage: Data persists even after the browser is closed.
- Session Storage: Data persists only during the current browser session and is cleared when the tab is closed.
Discover more in the JS storage with free video tutorial.
Use the localStorage.setItem(key, value) method.
Example:
localStorage.setItem(“name”, “John”);
Learn step-by-step in the Free JavaScript storage tutorial for beginners.
Use the localStorage.getItem(key) method.
Example:
let name = localStorage.getItem(“name”);
Watch this demonstrated in the JavaScript storage with free tutorial.
Session Storage is used similarly to Local Storage but with sessionStorage instead.
Example:
sessionStorage.setItem(“age”, “25”);
let age = sessionStorage.getItem(“age”);
Explore this topic in the JavaScript storage free course video.
- Limited storage size (usually 5MB).
- Only stores strings; objects need to be serialized (e.g., using JSON.stringify).
- Accessible by JavaScript, which can pose security risks if not managed properly.
Find detailed explanations in the JS storage with free video tutorial.
Yes, use the removeItem() method to delete specific items or clear() to remove all items.
Example:
localStorage.removeItem(“name”);
localStorage.clear(); // Clears all data
Learn how to implement this in the Free JavaScript storage tutorial for beginners.
- Cookies:
- Sent with every server request.
- Can have an expiration date.
- Smaller storage size (4KB).
Watch the differences explained in the JavaScript storage with free tutorial.
Data in Local Storage is accessible via JavaScript, so it’s not secure for sensitive information. Always encrypt sensitive data before storing. Explore best practices in the JavaScript storage free course video.
- Avoid storing sensitive information.
- Use try-catch to handle potential errors.
- Regularly clean up unused storage items.
Check out these tips in the JS storage with free video tutorial.