Javascript
  • intro.
  • 1 - Getting started
  • 2 - Basics
  • 3 - Functions and Scope
  • 4 - Advanced Concepts
  • 5 - JavaScript in the Browser
  • 6 - JavaScript and Browser Storage
  • 7 - Asynchronous JavaScript
  • 8 - Design Patterns
  • 9 - Frameworks Overview
  • 10 - Testing and Debugging
Powered by GitBook
On this page

6 - JavaScript and Browser Storage

Introduction to Browser Storage

Browser storage allows web applications to store data directly in the user's browser, making it possible to maintain data between page refreshes or sessions. This is particularly useful for saving user preferences, form data, or application state. In this chapter, we will explore three main types of browser storage: LocalStorage, SessionStorage, and Cookies.

LocalStorage

What is LocalStorage?

  • LocalStorage: A way to store key-value pairs in a web browser with no expiration date. Data persists even after the browser is closed and reopened.

    • Capacity: Typically stores around 5-10MB of data.

    • Data Type: Stores everything as a string.

Using LocalStorage

  • Setting Items: Use localStorage.setItem(key, value) to add data.

    • Example:

      localStorage.setItem("username", "JohnDoe");
  • Getting Items: Use localStorage.getItem(key) to retrieve data.

    • Example:

      const username = localStorage.getItem("username");
      console.log(username);  // Output: "JohnDoe"
  • Removing Items: Use localStorage.removeItem(key) to remove a specific key.

    • Example:

      localStorage.removeItem("username");
  • Clearing All Items: Use localStorage.clear() to remove all items.

    • Example:

      localStorage.clear();

Use Cases of LocalStorage

  • User Preferences: Save theme settings (e.g., dark mode or light mode).

  • Form Data: Store data in forms to prevent users from losing information on refresh.

SessionStorage

What is SessionStorage?

  • SessionStorage: Similar to LocalStorage, but with shorter lifetime—data is only available for the duration of the page session (until the browser or tab is closed).

    • Capacity: Typically stores around 5-10MB of data.

    • Data Type: Stores everything as a string.

Using SessionStorage

  • Setting Items: Use sessionStorage.setItem(key, value) to add data.

    • Example:

      sessionStorage.setItem("sessionUser", "JaneDoe");
  • Getting Items: Use sessionStorage.getItem(key) to retrieve data.

    • Example:

      const sessionUser = sessionStorage.getItem("sessionUser");
      console.log(sessionUser);  // Output: "JaneDoe"
  • Removing Items: Use sessionStorage.removeItem(key) to remove a specific key.

    • Example:

      sessionStorage.removeItem("sessionUser");
  • Clearing All Items: Use sessionStorage.clear() to remove all items.

    • Example:

      sessionStorage.clear();

Use Cases of SessionStorage

  • Temporary Data Storage: Store temporary data like form progress or short-lived session data.

  • Shopping Cart: Maintain shopping cart data while users navigate through the site.

Cookies

What are Cookies?

  • Cookies: Small pieces of data sent from a website and stored in the user's browser. Cookies have an expiration date and are often used for tracking and identifying users.

    • Size Limit: Typically around 4KB per cookie.

    • Data Type: Stores everything as a string.

Creating and Accessing Cookies

  • Setting Cookies: Use document.cookie to set cookies.

    • Example:

      document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";
    • Explanation:

      • username=JohnDoe: The key-value pair to store.

      • expires: The expiration date of the cookie.

      • path: Determines where the cookie is accessible (default is current page).

  • Getting Cookies: Use document.cookie to read all cookies, but parsing is required.

    • Example:

      const cookies = document.cookie;
      console.log(cookies);  // Output: "username=JohnDoe; sessionToken=abc123"
  • Deleting Cookies: Set the cookie's expiration date to a past date to delete it.

    • Example:

      document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";

Use Cases of Cookies

  • Authentication: Store session IDs or authentication tokens.

  • Tracking: Track user behavior for analytics purposes.

Differences Between LocalStorage, SessionStorage, and Cookies

Feature
LocalStorage
SessionStorage
Cookies

Lifetime

Permanent (until cleared)

Session-only (until tab or browser is closed)

Defined expiration date

Capacity

~5-10MB

~5-10MB

~4KB per cookie

Data Type

String

String

String

Accessibility

Same-origin pages

Same-origin pages

Sent with HTTP requests

Best Practices for Browser Storage

  • Use Appropriate Storage: Choose the storage type that best suits your data's lifetime.

    • Use LocalStorage for long-term storage of user preferences.

    • Use SessionStorage for data that should only persist while the user is on the page.

    • Use Cookies for data that needs to be sent to the server, such as authentication tokens.

  • Avoid Storing Sensitive Information: Avoid storing passwords or sensitive data directly in browser storage due to security vulnerabilities.

  • JSON Serialization: Convert complex objects to JSON strings for storage and parse them back to objects when needed.

    • Example:

      const user = { name: "John", age: 30 };
      localStorage.setItem("user", JSON.stringify(user));
      const storedUser = JSON.parse(localStorage.getItem("user"));
      console.log(storedUser.name);  // Output: "John"

Summary

  • LocalStorage: Best for long-term storage with no expiration.

  • SessionStorage: Used for temporary storage during a single session.

  • Cookies: Useful for server-client communication, with expiration dates for data retention.

  • Best Practices: Use the right storage mechanism, avoid sensitive data, and serialize objects where necessary.


Next Chapter: Asynchronous JavaScript

Previous5 - JavaScript in the BrowserNext7 - Asynchronous JavaScript

Last updated 6 months ago