JavaScript Course
JavaScript
/
Advanced

IndexedDB

Definition

A low-level API for client-side storage of significant amounts of structured data, including files/blobs. It uses indexes to enable high-performance searches of this data.

Explain Like I'm New

LocalStorage is a tiny notepad. IndexedDB is a massive filing cabinet. It's an actual NoSQL database built right into your browser. It takes more work to set up, but it can hold hundreds of megabytes of data, search it incredibly fast, and runs asynchronously so it doesn't freeze the screen.

Real World Example

Google Docs uses IndexedDB to save your document offline. If your wifi cuts out, your keystrokes are saved to IndexedDB. When wifi returns, it syncs the database with the Google servers.

Common Use Cases

  • •Offline Progressive Web Apps (PWAs)
  • •Storing large files/images client-side
  • •Caching massive API responses

Interactive Example

// Raw IndexedDB is notoriously complex and uses old event listeners instead of Promises.
// In the real world, developers use wrapper libraries like `idb` or `localForage`.

// Example using the popular 'idb' wrapper library:
/*
import { openDB } from 'idb';

async function initDB() {
  const db = await openDB('my-store', 1, {
    upgrade(db) {
      db.createObjectStore('users', { keyPath: 'id' });
    },
  });

  // Add a user
  await db.put('users', { id: 123, name: 'Alice', age: 25 });

  // Retrieve a user
  const user = await db.get('users', 123);
  console.log(user.name);
}
*/

Interview Questions

basic

  • Why use IndexedDB over LocalStorage?

intermediate

  • Is IndexedDB synchronous or asynchronous?

advanced

  • What is the difference between IndexedDB and WebSQL?

Flash Cards

Question

Why use it over LocalStorage?

Click to reveal answer
Answer

1. Capacity (Hundreds of MBs vs 5MB). 2. Types (Stores Objects/Blobs natively, no JSON.stringify needed). 3. Performance (Async operations don't block the main thread). 4. Querying (Has indexes and cursors for fast searching).

Question

WebSQL vs IndexedDB?

Click to reveal answer
Answer

WebSQL was an old attempt to put a literal SQLite database in the browser. It was deprecated and removed from modern browsers because all browsers ended up just using the exact same SQLite backend, failing the requirement for independent browser implementations. IndexedDB is the official modern standard.