Menu

Log in

Sign up

From beginner to master of web design, coding, infrastructure operation, business development and marketing

  • COURSES
  • HTML & CSS Introduction
  • HTML & CSS Coding with AI
  • Linux Introduction
  • Docker Basics
  • Git & GitHub Introduction
  • JavaScript Coding with AI
  • Django Introduction
  • AWS Basics
  • Figma Introduction
  • SEO Tutorial for Beginners
  • SEO with AI
  • OTHERS
  • About
  • Terms of Service
  • Privacy Policy

© 2024 D-Libro. All Rights Reserved

JavaScript Coding with AIChapter 10. Browser Storage in JavaScript

Local Storage in JavaScript

Local Storage in JavaScript

Local Storage

Local storage in JavaScript provides a powerful way to store data directly on the user's browser. This feature allows developers to save data that persists even after the browser is closed, unlike session-based storage. With local storage, you can optimize web applications by enabling features like offline access and saving user preferences.

In this section, we’ll cover the following topics:

  • What is Local Storage in JavaScript?
  • Setting Up and Accessing Local Storage
  • Implementing Local Storage with AI Assistance
  • Best Practices for Using Local Storage

What is Local Storage?

Local storage is a built-in feature in modern web browsers that allows the storage of key-value pairs directly on a user’s device. It is commonly used in web applications to store data that persists even after the user refreshes or closes the browser. Unlike cookies, local storage does not send data to the server with every HTTP request, making it more efficient for client-side storage. It provides a simple way to store data like user preferences (e.g., theme selection) or a shopping cart’s contents without the need for a backend or database.

How Local Storage Differs from Session Storage and Cookies

To understand the differences, let’s start by defining session storage and cookies:

Session Storage:

  • Session storage is similar to local storage but has a shorter lifespan. It stores data only for the duration of the session, which ends when the browser tab or window is closed.
  • This is useful for temporary data, such as storing inputs in a form while a user navigates between pages.

Example:

// Setting a session storage item
sessionStorage.setItem("username", "JohnDoe");

// Getting the item
const username = sessionStorage.getItem("username");
console.log(username); // Output: JohnDoe

// Data is cleared when the tab or window is closed.

Cookies:

  • Cookies are small pieces of data stored on the client-side but sent with every HTTP request to the server. They are often used for authentication, analytics, or tracking.
  • Cookies have additional properties, such as expires and secure, to control their lifespan and ensure secure transmission.

Example:

// Setting a cookie in JavaScript
document.cookie =
  "username=JohnDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";

// Reading cookies
console.log(document.cookie); // Output: username=JohnDoe

Local Storage:

  • Local storage is designed for storing larger amounts of data on the client-side, up to 5MB (varies by browser). Unlike cookies, data stored in local storage doesn’t automatically expire and isn’t sent to the server with each HTTP request.

Example:

// Setting a local storage item
localStorage.setItem("theme", "dark");

// Getting the item
const theme = localStorage.getItem("theme");
console.log(theme); // Output: dark

// Data persists even after the browser is closed.

Why Server-Side Storage is Still Important

While local storage, session storage, and cookies are convenient for client-side data management, they have limitations. If you need to store data for a long time, across multiple devices, or with enhanced security, server-side storage is essential.

Key reasons to use server-side storage:

  • Data Persistence: Server-side storage ensures data remains available even if the user clears their browser storage.
  • Cross-Device Access: Users can access the same data from multiple devices by syncing it through server-side solutions.
  • Enhanced Security: Sensitive data, such as payment details or passwords, should always be stored server-side with robust encryption methods to prevent client-side vulnerabilities.
  • Scalability: Server-side databases are better suited for managing large datasets efficiently.

For best results, combine client-side and server-side storage where appropriate. Use local storage for temporary or frequently accessed data, and rely on the server for critical, long-term data management.

Setting Up and Accessing Local Storage

Using localStorage.setItem() and localStorage.getItem()

The setItem() method allows you to store data in the form of key-value pairs, while getItem() retrieves it.

// Setting an item
localStorage.setItem("username", "JaneDoe");

// Retrieving an item
const username = localStorage.getItem("username");
console.log(username); // Output: JaneDoe

Removing Items with localStorage.removeItem() and localStorage.clear()

To delete specific items, use removeItem(). To clear all stored data, use clear().

// Removing a specific item
localStorage.removeItem("username");

// Clearing all items
localStorage.clear();

Implementing Local Storage with AI Assistance

Local storage’s integration into web development becomes even more efficient with AI tools. These tools help automate the process of data management and provide prompts to enhance functionality.

Preparing for Practice Files

This course takes a hands-on approach, allowing you to apply the techniques covered in real-world scenarios. We'll be using a structured folder layout. Before proceeding with the examples, please ensure the following files are prepared:

/your-project-folder/  
  |─10-01-local-storage/ (<- sub-folder)  
    |─ example-1.css  
    |─ example-1.html  
    |─ example-1.js  

For your convenience, these files are also available on our GitHub repository.

AI Case: Storing User Preferences

Storing user preferences in local storage allows applications to retain user-specific configurations like themes, layout settings, or language preferences. AI tools can generate boilerplate code for this use case.

Sample AI prompt:

Generate JavaScript code to save, retrieve, and clear a user's preferred theme using local storage, while keeping the latest theme active after clearing the local storage.

Sample code output:

10-01-local-storage/example-1.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="example-1.css" />
    <title>User Preferences with Local Storage</title>
  </head>
  <body>
    <div class="container">
      <h1>Theme Preferences</h1>
      <p>
        Use the buttons below to toggle between Light Mode and Dark Mode or
        clear the theme preference from local storage.
      </p>
      <button id="darkModeToggle">Toggle Dark Mode</button>
      <button id="clearStorage">Clear Local Storage</button>
    </div>
    <script src="example-1.js"></script>
  </body>
</html>

10-01-local-storage/example-1.css
/* General reset */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* Body Styling */
body {
  font-family: "Arial", sans-serif;
  background-color: white;
  color: black;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

body.dark-mode {
  background-color: #121212;
  color: #e0e0e0; /* Updated for better contrast and readability */
}

/* Centered Container */
.container {
  text-align: center;
  padding: 20px;
  max-width: 400px;
  border: 1px solid #ddd;
  border-radius: 10px;
  background: #f9f9f9;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

body.dark-mode .container {
  background-color: #1e1e1e;
  border-color: #333;
}

/* Button Styling */
button {
  padding: 10px 20px;
  margin: 10px;
  font-size: 16px;
  color: #fff;
  background-color: #007bff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

button:hover {
  background-color: #0056b3;
}

body.dark-mode button {
  background-color: #28a745;
}

body.dark-mode button:hover {
  background-color: #218838;
}

10-01-local-storage/example-1.js
const toggleButton = document.getElementById("darkModeToggle");
const clearButton = document.getElementById("clearStorage");

// Event listener to toggle Dark Mode
toggleButton.addEventListener("click", () => {
  document.body.classList.toggle("dark-mode");
  const isDarkMode = document.body.classList.contains("dark-mode");
  // Save the theme to local storage
  localStorage.setItem("theme", isDarkMode ? "dark" : "light");
});

// Event listener to clear local storage while keeping the current theme
clearButton.addEventListener("click", () => {
  localStorage.removeItem("theme");
  alert("Local storage cleared. The current theme remains unchanged.");
});

// Load the saved theme from local storage
const savedTheme = localStorage.getItem("theme");
if (savedTheme === "dark") {
  document.body.classList.add("dark-mode");
}

Instructions to see the results:

Save the code above in each file. Open the HTML file in your browser.

  • Use the "Toggle Dark Mode" button to switch between Light Mode and Dark Mode. Your preference will be saved in local storage and persist after refreshing or reopening the browser.
  • Use the "Clear Local Storage" button to remove the saved preference while keeping the current theme unchanged.

By observing the behavior after clearing the local storage, you can understand how it interacts with the application.

Watch this video to see it in action:

To explore how Local Storage works, you can also visit the following link:

Demo Web Page 41

Reference links:

MDN Web Docs: Window.localStorage

W3Schools: Window.localStorage Property

More Topics to Explore

Styles in Figma

Styles in Figma

How to Enhance Forms with Labels

Labels

Maximizing Layout Flexibility with flex-grow

flex-grow

Javascript Basics

Javascript Basics

Navigating the Main Axis and Cross Axis in Flex Box

Main Axis and Cross Axis

Styles in Figma

Styles in Figma

How to Enhance Forms with Labels

Labels

Maximizing Layout Flexibility with flex-grow

flex-grow

Javascript Basics

Javascript Basics

Navigating the Main Axis and Cross Axis in Flex Box

Main Axis and Cross Axis

Tags:

JavaScript

Web Development

Local Storage

Client-Side Storage

User Preferences

JavaScript Coding with AI
Course Content

Chapter 1. Key Javascript Concepts And Coding With AI

What Is Javascript?

Start Writing Javascript With AI Assistance

Javascript Basics

Chapter 2. Javascript Basic Syntax

Statements And Expressions

Variables

Case Sensitivity

Case Style For Javascript

Reserved Words

Escape Characters

Semi-Colons

Spaces And Indentation

Comments

Literals and Data Types

Arrays

Template Literal

Brackets

Chapter 3. Operators In Javascript

Arithmetic Operators

Increment And Decrement Operators

Assignment Operators

Comparison Operators

Conditional Operators

Logical Operators

Logical Assignment Operators

Nullish Coalescing Operator

Optional Chaining

Three Dots in JavaScript

Chapter 4. Control Statements In Javascript

If Statement

Switch Statement

While Statement

For Statement

Chapter 5. Functions In Javascript

How To Create A Function

Functions With Default Parameter

Return Values

Variable Scope

Function Hoisting

This in JavaScript

Anonymous Function

Arrow Function

Higher-Order Function

Chapter 6. Objects, Methods, And Classes In Javascript

Objects

Methods

Array Methods

Classes

Immutable and Mutable Data Types

What Is JSON?

Chapter 7. Manipulating Web Pages With Javascript

BOM And DOM

getElementBy vs. querySelector

Event Handler And Event Listener

Event Object

Mouse Events

Keyboard Events

Focus And Blur Events

Form Events

Window Events

Touch Events

Drag And Drop Events

Animation Events

Media Events, Network Events, and More

Javascript Custom Events

Chapter 8. Web API And Ajax Javascript Coding

What Are The HTTP Methods?

What Is Ajax?

Implementing Web APIs

Chapter 9. Modules And Libraries In Javascript

Javascript Libraries And Frameworks

NPM: Javascript Package Manager

How To Use jQuery

Chapter 10. Browser Storage in JavaScript

Local Storage

Session Storage

Cookies

Chapter 11. Building Web Applications in JavaScript

Node.js and Express.js

Database Integration: Mongo DB

Developing a Chat Application

Canvas HTML Tag and JavaScript

Creating an Online Drawing Tool

Chapter 1. Key Javascript Concepts And Coding With AI

What Is Javascript?

Start Writing Javascript With AI Assistance

Javascript Basics

Chapter 2. Javascript Basic Syntax

Statements And Expressions

Variables

Case Sensitivity

Case Style For Javascript

Reserved Words

Escape Characters

Semi-Colons

Spaces And Indentation

Comments

Literals and Data Types

Arrays

Template Literal

Brackets

Chapter 3. Operators In Javascript

Arithmetic Operators

Increment And Decrement Operators

Assignment Operators

Comparison Operators

Conditional Operators

Logical Operators

Logical Assignment Operators

Nullish Coalescing Operator

Optional Chaining

Three Dots in JavaScript

Chapter 4. Control Statements In Javascript

If Statement

Switch Statement

While Statement

For Statement

Chapter 5. Functions In Javascript

How To Create A Function

Functions With Default Parameter

Return Values

Variable Scope

Function Hoisting

This in JavaScript

Anonymous Function

Arrow Function

Higher-Order Function

Chapter 6. Objects, Methods, And Classes In Javascript

Objects

Methods

Array Methods

Classes

Immutable and Mutable Data Types

What Is JSON?

Chapter 7. Manipulating Web Pages With Javascript

BOM And DOM

getElementBy vs. querySelector

Event Handler And Event Listener

Event Object

Mouse Events

Keyboard Events

Focus And Blur Events

Form Events

Window Events

Touch Events

Drag And Drop Events

Animation Events

Media Events, Network Events, and More

Javascript Custom Events

Chapter 8. Web API And Ajax Javascript Coding

What Are The HTTP Methods?

What Is Ajax?

Implementing Web APIs

Chapter 9. Modules And Libraries In Javascript

Javascript Libraries And Frameworks

NPM: Javascript Package Manager

How To Use jQuery

Chapter 10. Browser Storage in JavaScript

Local Storage

Session Storage

Cookies

Chapter 11. Building Web Applications in JavaScript

Node.js and Express.js

Database Integration: Mongo DB

Developing a Chat Application

Canvas HTML Tag and JavaScript

Creating an Online Drawing Tool

FAQ: Local Storage in JavaScript

What is Local Storage in JavaScript?

Local storage in JavaScript provides a powerful way to store data directly on the user's browser. This feature allows developers to save data that persists even after the browser is closed, unlike session-based storage. With local storage, you can optimize web applications by enabling features like offline access and saving user preferences.

How does Local Storage differ from Session Storage and Cookies?

Local storage is designed for storing larger amounts of data on the client-side, up to 5MB (varies by browser). Unlike cookies, data stored in local storage doesn’t automatically expire and isn’t sent to the server with each HTTP request. Session storage, on the other hand, stores data only for the duration of the session, which ends when the browser tab or window is closed. Cookies are small pieces of data sent with every HTTP request to the server and are often used for authentication, analytics, or tracking.

Why is Server-Side Storage still important?

While local storage, session storage, and cookies are convenient for client-side data management, they have limitations. Server-side storage is essential for data persistence, cross-device access, enhanced security, and scalability. It ensures data remains available even if the user clears their browser storage and allows users to access the same data from multiple devices.

How do you set up and access Local Storage?

To store data in local storage, use the localStorage.setItem() method, which stores data in the form of key-value pairs. To retrieve data, use localStorage.getItem(). To delete specific items, use localStorage.removeItem(), and to clear all stored data, use localStorage.clear().

How can AI assist in implementing Local Storage?

AI tools can enhance the integration of local storage into web development by automating data management processes and providing prompts to improve functionality. For example, AI can generate boilerplate code for storing user preferences, such as themes or layout settings, in local storage.