Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 51 - Introduction to Browser Storage

What is Browser Storage?

Browser storage allows web applications to store data on a user's browser. JavaScript provides two main types of storage:

  1. localStorage – Stores data with no expiration. Data remains even after the browser is closed.
  2. sessionStorage – Stores data for the duration of a page session. Data is lost when the page is closed.

Why Use Browser Storage?

  • Saves user preferences.
  • Stores temporary data for faster page loading.
  • Reduces reliance on server-side storage.

The Difference Between localStorage and sessionStorage

Feature localStorage sessionStorage
Data Lifespan Permanent (until manually cleared) Session-based (deleted when the page is closed)
Scope Accessible across multiple tabs/windows of the same origin Available only within the same tab
Size Limit ~5MB per domain ~5MB per domain
Use Case Storing user preferences, theme settings, authentication tokens Storing temporary form data, cart items for session

Accessing Browser Storage

Browser storage is accessible via the window object.

// Access localStorage and sessionStorage
console.log(window.localStorage); 
console.log(window.sessionStorage);

Summary

  • localStorage keeps data until it's manually deleted.
  • sessionStorage keeps data only for the current session.
  • Both store key-value pairs and can be accessed via JavaScript.

In the next lesson, we will learn how to store, retrieve, and remove data using localStorage and sessionStorage.

Try Your Hand

  1. Open your browser's Developer Console (F12 or Ctrl+Shift+I -> Console tab).
  2. Type window.localStorage and window.sessionStorage to explore the stored data.
  3. Experiment with adding, retrieving, and deleting values.

Stay tuned for Day 52, where we will explore storing and retrieving data with localStorage!