JavaScript: Step 12- Browser Storage (localStorage/sessionStorage)

image 2

Play Store Application link – Java to JavaScript in 13 Steps – App on Google Play

Browser storage allows web browsers to store data locally on the user’s device, providing two primary types: localStorage and sessionStorage.

Comparing to Core Java:

  • Core Java Comparison: Core Java does not have a direct equivalent of localStorage or sessionStorage, but data persistence in Java can be handled using file I/O, serialization, or databases. For instance, storing user preferences or application settings can be done using file operations or databases.

Tabular Comparisons:

FeaturelocalStoragesessionStorage
Data StoredWithout expiration dateFor a single session or tab
Data DeletedExplicitly by user or applicationWhen the user closes the tab/window or browser

Text Diagram:

Browser Storage
  |
localStorage       sessionStorage
  |                    |
Data without         Data for a single
expiration date      session or tab
  |                    |
Explicitly deleted   Deleted when user
by user or website   closes tab/window,
or when browser      or when browser is closed
is closed            |
                     |

Basic Programs:

1. Storing and Retrieving Data Using localStorage:

// Store data
localStorage.setItem('name', 'John Doe');

// Retrieve data
const name = localStorage.getItem('name');
console.log(name); // "John Doe"

Core Java Comparison: In core Java, you might use file I/O to achieve a similar result:

import java.io.*;

public class LocalStorageExample {
    public static void main(String[] args) throws IOException {
        // Store data
        try (PrintWriter out = new PrintWriter(new FileWriter("data.txt"))) {
            out.println("John Doe");
        }

        // Retrieve data
        try (BufferedReader in = new BufferedReader(new FileReader("data.txt"))) {
            String name = in.readLine();
            System.out.println(name); // "John Doe"
        }
    }
}

2. Storing and Retrieving Data Using sessionStorage:

// Store data
sessionStorage.setItem('name', 'John Doe');

// Retrieve data
const name = sessionStorage.getItem('name');
console.log(name); // "John Doe"

Core Java Comparison: While Java does not have a direct session-based storage mechanism, you can simulate session-based data storage using temporary files or memory:

import java.util.HashMap;
import java.util.Map;

public class SessionStorageExample {
    public static void main(String[] args) {
        // Simulate session-based storage with a HashMap
        Map<String, String> sessionData = new HashMap<>();
        sessionData.put("name", "John Doe");

        // Retrieve data
        String name = sessionData.get("name");
        System.out.println(name); // "John Doe"
    }
}

3. Removing Data from localStorage:

localStorage.removeItem('name');

Core Java Comparison: In core Java, you can delete a file to simulate data removal:

import java.io.File;

public class DeleteDataExample {
    public static void main(String[] args) {
        File file = new File("data.txt");
        if (file.delete()) {
            System.out.println("File deleted successfully");
        } else {
            System.out.println("Failed to delete the file");
        }
    }
}

4. Removing All Data from localStorage:

localStorage.clear();

Core Java Comparison: Clearing all data in core Java can be done by deleting all files in a directory or clearing a database:

import java.io.File;

public class ClearDataExample {
    public static void main(String[] args) {
        File folder = new File("data_directory");
        File[] files = folder.listFiles();
        if (files != null) {
            for (File file : files) {
                file.delete();
            }
            System.out.println("All files deleted successfully");
        }
    }
}

To Run These Programs:

  1. JavaScript:
  • Create a .js file with the JavaScript code.
  • Include this JavaScript file in an HTML file.
  • Open the HTML file in a web browser to see the output in the console.
<pre class="wp-block-syntaxhighlighter-code"><!-- index.html -->
<!DOCTYPE html>
<html>
    <head>
        <title>Browser Storage Example</title>
    </head>
    <body>
        <a href="http://script.js">http://script.js</a>
    </body>
</html></pre>
// script.js
localStorage.setItem('name', 'John Doe');
const name = localStorage.getItem('name');
console.log(name); // "John Doe"
  1. Core Java:
  • Compile and run the Java code using a Java IDE or command line.

Leave a Reply

Your email address will not be published. Required fields are marked *