IndexedDB characteristics
- IndexedDB consists of the following structural components.
- Databases: It is the highest level of IndexedDB that contains one or object stores. IndexedDB can have one or more databases, but one database per web application will be.
- Object Store: The object store is a bucket that one can use to store data with associated indexes. It contains records stored as key-value pairs. It is similar to the table in a SQL database.
- Indexes: Indexes help to query data in the database by properties of the objects.
- IndexedDB maintains the transactional model that ensures data integrity in the database.
- IndexedDB operations are primarily asynchronous.
- IndexedDB follows the same-origin policy. Each origin has its own set of databases. An origin is a domain, protocol, and port of a URL document. One origin can't access data from another origin.
http://www.google.com and https://www.google.com are not exact origins as their protocols are different (HTTP and HTTPS).
- It can store large amounts of data without a persistent internet connection. For example, Google docs use indexedDB for storing a cached document in the browser and synchronizes with the server once in a while.
IndexedDB operations
Opening a connection to a database and Creating object-store
Opening a database is an asynchronous operation. We need to send a request to extend our database and then listen for events to know when it's ready. We'll open a Demo DB. If it doesn't exist yet then it will get created when we send the request. The two below say we're asking for version 2 of our database where only one version exists at any time, but one can use the version number to upgrade old data; as we'll see -
var db = null, // This is their to be used once we have our database
request = window.indexedDB.open("DemoDB", 2);
// This listens for the successful opening of the db and will be called after the 'onupgradeneeded' util runs, if it does at all
request.onsuccess = function() {
db = request.result; // then we have an access to our database!
doThingsWithDB(db);
};
// But if our database didn't exist before, or it was an older version than what we requested,
// the `onupgradeneeded` event will be fired.
// We can use this to set up a new database and upgrade an old one with new object store
request.onupgradeneeded = function(event) {
db = request.result;
// If the 'oldVersion' var is less than 1 then it depicts that the database didn't exist. Let's set it up
if (event.oldVersion < 1) {
// We'll create a new "things" store with `autoIncrement`ing keys
var store = db.createObjectStore("things", { autoIncrement: true });
}
// In version 2 of our database, we are creating a new index same as the name of each item
if (event.oldVersion < 2) {
// Let's load the object store and create an index
var store = request.transaction.objectStore("things");
store.createIndex("by_name", "name");
}
};
// Handle any errors
request.onerror = function() {
console.error("Something went wrong when we tried to request the database!");
};

You can also try this code with Online Javascript Compiler
Run Code
Inserting data into object-store
Anything which needs to happen with data in an Indexed DB database occurs in a transaction. Here we will see how to
// Here, to create a new transaction; we'll use the default "read-only" mode, and the things store
var transaction = db.transaction(["things"]);
// Transactions use events such as database open requests. Let's listen for success
transaction.oncomplete = function() {
console.log("All done!");
};
// And make sure we handle errors
transaction.onerror = function() {
console.log("Something went wrong with our transaction: ", transaction.error);
};
// Now since everything is set up, let's get our things stored and load some objects!
var store = transaction.objectStore("things");
// We'll load the coffee_cup object which we added in Adding objects
var request = store.get("coffee_cup");
// Let's open a listener so that we can check whether everything works
request.onsuccess = function(event) {
// All done, let's log our object to the console
console.log(request.result);
};
// That was a lengthy util for a basic retrieval and if one just wanted to get
// a single object and doesn't care about errors, then it can shorten things a lot
db.transaction("things").objectStore("things")
.get("coffee_cup").onsuccess = e => console.log(e.target.result);

You can also try this code with Online Javascript Compiler
Run Code
Retrieving data from an object store
We'll use the utils that we set up in Opening a database for retrieving data. See the below snippets for a better understanding.
// Here, to create a new transaction, we'll use the default "readonly" mode and the things store
var transaction = db.transaction(["things"]);
// Transactions generally use events, just like database open requests. Let's listen for success
transaction.oncomplete = function() {
console.log("All done!");
};
// And make sure we handle errors
transaction.onerror = function() {
console.log("Something went wrong with our transaction: ", transaction.error);
};
// Now that everything is set, let's get our things to store and load some objects!
var store = transaction.objectStore("things");
// Here we'll load the 'coffee_cup' object we added in Adding objects
var request = store.get("coffee_cup");
// Let's open a listener so we can check whether everything worked
request.onsuccess = function(event) {
// All set, let's try logging our object to the console
console.log(request.result);
};
// That was pretty lengthy util for a basic retrieval task. If one just wants to get
// a single object and is willing to ignore the errors, then they can shorten things a lot
db.transaction("things").objectStore("things")
.get("coffee_cup").onsuccess = e => console.log(e.target.result);

You can also try this code with Online Javascript Compiler
Run Code
FAQs
1. What is an IndexedDB?
IndexedDB is a javascript-based object-oriented database that works as client-side storage of a significant amount of data in a browser. IndexedDB store and retrieve data that are indexed with a key. The IndexedDB API uses these indexes for high-performance searches of this data.
2. When should one use an indexedDB vs the local storage?
One should generally go by using an IndexedDB for storing extensive data in the browser. In contrast, they should use the LocalStorage for small amounts of data that one needs synchronous access to.
Key Takeaways
This article covered what IndexedDB is and how it works in the browser.
Check out the Coding Ninjas Studio library to better grasp the data structures and algorithms and the guided path for learning javascript from basics.
Side by side, you can also practice a wide variety of coding questions commonly asked in interviews in Coding Ninjas Studio. Along with coding questions, you can also find the interview experience of scholars working in renowned product-based companies here.
Happy learning!