📖 JavaScript Local Storage

LocalStorage is a web storage API that allows you to store data in the browser persistently. This means the data remains available even after the user closes the browser. LocalStorage is particularly useful for saving user preferences, session data, and other small pieces of data that need to persist between page reloads.

Note: LocalStorage data is part of the browser data and can be deleted if a user clears their browser data. This includes clearing site data, cookies, or browsing history. However, clearing the browser cache typically does not affect LocalStorage data.

Core Principles

Basic Operations

localStorage.setItem(key, value)
Stores a key-value pair in LocalStorage.
localStorage.getItem(key)
Retrieves the value associated with the given key from LocalStorage.
localStorage.removeItem(key)
Removes the key-value pair associated with the given key from LocalStorage.
localStorage.clear()
Clears all data from LocalStorage.

Note: localStorage might not work as expected in in some browsers (e.g., Firefox). You might try different browsers if you want to test this from the console.

Setting and Getting Data


// Setting data
localStorage.setItem('username', 'JohnDoe');

// Getting data
const username = localStorage.getItem('username');
console.log(username); // Output: JohnDoe
        

Removing and Clearing Data


// Removing data
localStorage.removeItem('username');

// Clearing all data
localStorage.clear();
        

Using JSON with LocalStorage

LocalStorage can only store strings. To store complex data structures like objects or arrays, you need to serialize them into a string format using JSON.

JSON.stringify(object)
Converts an object or array into a JSON string.
JSON.parse(string)
Converts a JSON string back into an object or array.

Storing and Retrieving Objects


// Storing an object
const user = { name: 'John Doe', age: 30 };

// Convert the object to a JSON string and store it in localStorage
localStorage.setItem('user', JSON.stringify(user));

// Retrieving an object
// Retrieve the JSON string from localStorage and parse it back into an object
// If 'user' doesn't exist in localStorage, fall back to an empty object ({}) or array ([]) as appropriate.
const storedUser = JSON.parse(localStorage.getItem('user')) || {};

// Log the retrieved object or the fallback empty object
console.log(storedUser); // Output: { name: 'John Doe', age: 30 } or {} if 'user' doesn't exist
        

Putting It Into Action

Create an HTML file with the following structure and include the provided script. This script demonstrates how to use LocalStorage to store and retrieve user preferences.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>LocalStorage Example>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
</head>
<body>
    <div class="container mt-5">
        <h1>LocalStorage Example>
        <form id="userForm">
            <div class="mb-3">
                <label for="nameInput" class="form-label">Name:>
                <input type="text" id="nameInput" class="form-control" placeholder="Enter your name">
            >
            <div class="mb-3">
                <label for="ageInput" class="form-label">Age:>
                <input type="number" id="ageInput" class="form-control" placeholder="Enter your age">
            >
            <button type="submit" class="btn btn-primary">Save>
        >
        >

    <script>
        document.getElementById('userForm').addEventListener('submit', function(event) {
            event.preventDefault();
            const name = document.getElementById('nameInput').value;
            const age = document.getElementById('ageInput').value;
            const user = { name, age };
            localStorage.setItem('user', JSON.stringify(user));
            alert('User data saved!');
        });

        // Retrieve and display user data on page load
        document.addEventListener('DOMContentLoaded', function() {
            const storedUser = JSON.parse(localStorage.getItem('user'));
            if (storedUser) {
                document.getElementById('nameInput').value = storedUser.name;
                document.getElementById('ageInput').value = storedUser.age;
            }
        });
    >
>
>
        

Challenge

Extend the example to include a theme preference (light or dark mode) and save the user's choice in LocalStorage. Apply the selected theme when the page loads.


<form id="userForm">
    <div class="mb-3">
        <label for="nameInput" class="form-label">Name:>
        <input type="text" id="nameInput" class="form-control" placeholder="Enter your name">
    >
    <div class="mb-3">
        <label for="ageInput" class="form-label">Age:>
        <input type="number" id="ageInput" class="form-control" placeholder="Enter your age">
    >
    <div class="mb-3">
        <label for="themeSelect" class="form-label">Theme:>
        <select id="themeSelect" class="form-select">
            <option value="light">Light>
            <option value="dark">Dark>
        >
    >
    <button type="submit" class="btn btn-primary">Save>
>
        

// JavaScript Code
document.getElementById('userForm').addEventListener('submit', function(event) {
    event.preventDefault();
    const name = document.getElementById('nameInput').value;
    const age = document.getElementById('ageInput').value;
    const theme = document.getElementById('themeSelect').value;
    const user = { name, age, theme };
    localStorage.setItem('user', JSON.stringify(user));
    alert('User data saved!');
    applyTheme(theme);
});

// Retrieve and display user data on page load
document.addEventListener('DOMContentLoaded', function() {
    const storedUser = JSON.parse(localStorage.getItem('user'));
    if (storedUser) {
        document.getElementById('nameInput').value = storedUser.name;
        document.getElementById('ageInput').value = storedUser.age;
        document.getElementById('themeSelect').value = storedUser.theme;
        applyTheme(storedUser.theme);
    }
});

// Function to apply the selected theme
function applyTheme(theme) {
    document.body.className = theme;
}
        

References