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?