In this lesson, we will explore two important web storage mechanisms provided by modern browsers: Local Storage and Session Storage. These storage options allow you to store data on the client side, making it possible to save user preferences, session data, and more without involving a server.
What is Web Storage?
Web Storage is a way to store data in the browser. It is more secure and faster than using cookies. There are two types of web storage:
- Local Storage: Data stored here has no expiration time. It remains until explicitly deleted.
- Session Storage: Data stored here is only available for the duration of the page session. It is deleted when the page session ends (i.e., when the browser tab is closed).
Key Differences
Feature | Local Storage | Session Storage |
---|---|---|
Lifetime | Until explicitly deleted | Until the browser tab is closed |
Scope | Available across all tabs and windows | Available only within the tab |
Storage Limit | Typically 5-10 MB per origin | Typically 5-10 MB per origin |
Use Case | Long-term storage (e.g., user settings) | Short-term storage (e.g., form data) |
Using Local Storage
Storing Data
To store data in Local Storage, use the localStorage.setItem
method. It takes two arguments: a key and a value.
// Storing a string localStorage.setItem('username', 'JohnDoe'); // Storing a number (converted to string) localStorage.setItem('age', 30); // Storing an object (must be stringified) const user = { name: 'John', age: 30 }; localStorage.setItem('user', JSON.stringify(user));
Retrieving Data
To retrieve data, use the localStorage.getItem
method. It takes one argument: the key.
// Retrieving a string const username = localStorage.getItem('username'); console.log(username); // Output: JohnDoe // Retrieving a number (converted from string) const age = localStorage.getItem('age'); console.log(Number(age)); // Output: 30 // Retrieving an object (must be parsed) const user = JSON.parse(localStorage.getItem('user')); console.log(user); // Output: { name: 'John', age: 30 }
Removing Data
To remove data, use the localStorage.removeItem
method.
// Removing a specific item localStorage.removeItem('username'); // Clearing all items localStorage.clear();
Using Session Storage
Storing Data
To store data in Session Storage, use the sessionStorage.setItem
method. It works similarly to Local Storage.
// Storing a string sessionStorage.setItem('sessionUser', 'JaneDoe'); // Storing a number (converted to string) sessionStorage.setItem('sessionAge', 25); // Storing an object (must be stringified) const sessionUser = { name: 'Jane', age: 25 }; sessionStorage.setItem('sessionUserObj', JSON.stringify(sessionUser));
Retrieving Data
To retrieve data, use the sessionStorage.getItem
method.
// Retrieving a string const sessionUser = sessionStorage.getItem('sessionUser'); console.log(sessionUser); // Output: JaneDoe // Retrieving a number (converted from string) const sessionAge = sessionStorage.getItem('sessionAge'); console.log(Number(sessionAge)); // Output: 25 // Retrieving an object (must be parsed) const sessionUserObj = JSON.parse(sessionStorage.getItem('sessionUserObj')); console.log(sessionUserObj); // Output: { name: 'Jane', age: 25 }
Removing Data
To remove data, use the sessionStorage.removeItem
method.
// Removing a specific item sessionStorage.removeItem('sessionUser'); // Clearing all items sessionStorage.clear();
Practical Exercise
Task
- Create a simple HTML form that allows a user to input their name and age.
- When the form is submitted, store the user's name and age in Local Storage.
- Display the stored name and age on the page.
- Add a button to clear the stored data.
Solution
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Local Storage Example</title> </head> <body> <form id="userForm"> <label for="name">Name:</label> <input type="text" id="name" required> <label for="age">Age:</label> <input type="number" id="age" required> <button type="submit">Submit</button> </form> <div id="userData"></div> <button id="clearData">Clear Data</button> <script> document.getElementById('userForm').addEventListener('submit', function(event) { event.preventDefault(); const name = document.getElementById('name').value; const age = document.getElementById('age').value; localStorage.setItem('name', name); localStorage.setItem('age', age); displayUserData(); }); document.getElementById('clearData').addEventListener('click', function() { localStorage.clear(); displayUserData(); }); function displayUserData() { const name = localStorage.getItem('name'); const age = localStorage.getItem('age'); const userDataDiv = document.getElementById('userData'); if (name && age) { userDataDiv.innerHTML = `Name: ${name}, Age: ${age}`; } else { userDataDiv.innerHTML = 'No data stored'; } } // Display data on page load displayUserData(); </script> </body> </html>
Explanation
- HTML Form: A simple form with fields for name and age.
- Form Submission: When the form is submitted, the data is stored in Local Storage.
- Display Data: The stored data is displayed on the page.
- Clear Data: A button to clear the stored data.
Conclusion
In this lesson, we learned about Local Storage and Session Storage, their differences, and how to use them to store, retrieve, and remove data. These storage mechanisms are powerful tools for enhancing the user experience by allowing data persistence on the client side. In the next lesson, we will delve into the Fetch API and AJAX to handle asynchronous data fetching.
JavaScript: From Beginner to Advanced
Module 1: Introduction to JavaScript
- What is JavaScript?
- Setting Up Your Development Environment
- Your First JavaScript Program
- JavaScript Syntax and Basics
- Variables and Data Types
- Basic Operators
Module 2: Control Structures
Module 3: Functions
- Defining and Calling Functions
- Function Expressions and Arrow Functions
- Parameters and Return Values
- Scope and Closures
- Higher-Order Functions
Module 4: Objects and Arrays
- Introduction to Objects
- Object Methods and 'this' Keyword
- Arrays: Basics and Methods
- Iterating Over Arrays
- Array Destructuring
Module 5: Advanced Objects and Functions
- Prototypes and Inheritance
- Classes and Object-Oriented Programming
- Modules and Import/Export
- Asynchronous JavaScript: Callbacks
- Promises and Async/Await
Module 6: The Document Object Model (DOM)
- Introduction to the DOM
- Selecting and Manipulating DOM Elements
- Event Handling
- Creating and Removing DOM Elements
- Form Handling and Validation
Module 7: Browser APIs and Advanced Topics
- Local Storage and Session Storage
- Fetch API and AJAX
- WebSockets
- Service Workers and Progressive Web Apps (PWAs)
- Introduction to WebAssembly
Module 8: Testing and Debugging
Module 9: Performance and Optimization
- Optimizing JavaScript Performance
- Memory Management
- Efficient DOM Manipulation
- Lazy Loading and Code Splitting
Module 10: JavaScript Frameworks and Libraries
- Introduction to React
- State Management with Redux
- Vue.js Basics
- Angular Basics
- Choosing the Right Framework