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

  1. Create a simple HTML form that allows a user to input their name and age.
  2. When the form is submitted, store the user's name and age in Local Storage.
  3. Display the stored name and age on the page.
  4. 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

  1. HTML Form: A simple form with fields for name and age.
  2. Form Submission: When the form is submitted, the data is stored in Local Storage.
  3. Display Data: The stored data is displayed on the page.
  4. 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

Module 2: Control Structures

Module 3: Functions

Module 4: Objects and Arrays

Module 5: Advanced Objects and Functions

Module 6: The Document Object Model (DOM)

Module 7: Browser APIs and Advanced Topics

Module 8: Testing and Debugging

Module 9: Performance and Optimization

Module 10: JavaScript Frameworks and Libraries

Module 11: Final Project

© Copyright 2024. All rights reserved