Creating an In-Browser Database with JavaScript

As the applications you build get more complex, you’ll need to manage and save data.

An array is a list of things, and a Hash is a mapping of names and values. Using these together, we can create a simple, yet powerful data structure to hold a collection of records.

JavaScript refers to Hashes as "object literals". They are conceptually the same thing as hashes, maps, and dictionaries in other languages.

In this tutorial you’ll learn to use arrays and hashes to create an in-memory database. Then you’ll persist that data using HTML’s localStorage feature.

Creating a Data Structure

If we had an item with the following properties:

  • Name
  • Price
  • Color

We could define items in code like this, using object literals:

var item1 = {name: "Shirt", price: 25.00, color: "command gold"}
var item2 = {name: "Shirt", price: 25.00, color: "blue"}
var item3 = {name: "Shirt", price: 25.00, color: "red"}

But more importantly, we can create a collection of items by using an array:

var items = [item1, item2, item3];

We can then access the first item by its index:

items[0];

That fetches the object from the first index. And that means we can get the name of the first item with

items[0]["name"];

We know that 0 is the first index, and therefore the last index is one less than the number of items in the array. An array has a .length property that tells us how many things are in an array.

So to get the last item, we can do

items[items.length - 1];

And we can get the price of the last item with

items[items.length - 1]["price"];

And that means we can easily print these items out using a loop.

for (var index = 0, length = items.length; index < length; index++) {

}

Inside of the loop we can access the item using the index variable:

for (var index = 0, length = items.length; index < length; index++) {
  console.log(items[index]["name"]);
}

Here’s a more elaborate version of our program:

/*
 Define an array of items
*.
var items = [
  {name: "Shirt", price: 25.00, color: "command gold"},
  {name: "Shirt", price: 25.00, color: "blue"},
  {name: "Shirt", price: 25.00, color: "red"},
];

// print out items

var output = "";

for (var index = 0; index < items.length; index++) {
  output += "<h2>" + items[index]["name"] + "</h2>";
  output += "<p>Color: " + items[index]["color"] + "</p>";
  output += "<p>Price: $" + items[index]["price"].toFixed(2) + "</p>";
}

document.write(output);

What about adding an item? Well, we just need to create a new item, populate its fields, and push it onto the array:

// create item
var item = {};

// add values to fields
item["name"] = prompt("What is the item name?");
item["color"] = prompt("What is the item's color?");
item["price"] = prompt("What is the item's price?");

// add to items.
items.push(item);

Unfortunately if we reload the page, this data is gone forever.

Persisting Data

JavaScript in the browser cannot write to your hard drive. But other programming languages support writing directly to files, and this approach of building up a data structure is very common in mobile, desktop, and web programming. Web sites from Flickr to Facebook use JSON, which is nothing more than arrays and hashes, to transfer data around the web. This data is routinely “serialized” to JSON, which means it’s converted to a string. That string is transferred to another server or downloaded to a client, where it is deserialized back to objects.

// converting our items data structure to JSON:
var jsonData = JSON.stringify(items);

// converting JSON back to items
items = JSON.parse(jsonData);

So one way to persist data is with the browser’s localStorage feature. We can store JSON data in localStorage in our browser.

var jsonData = JSON.stringify(items);
localStorage.setItem("items", jsonData);

Then we can pull it out later:

jsonData = localStorage.getItem("items");
items = JSON.parse(jsonData);

Here’s a version of our program that checks for data in the localStorage of the browser. If it finds it, it uses it. If not, it populates default values:

var jsonData;
var items;

// attempt to get items from localstorage
jsonData = localStorage.getItem("items");

// Check to see if we got them.
if ( jsonData ) {
  
  // converting JSON back to items
  items = JSON.parse(jsonData);
  
} else {

  // No items found. Make some.
  items = [
    {name: "Shirt", price: 25.00, color: "command gold"},
    {name: "Shirt", price: 25.00, color: "blue"},
    {name: "Shirt", price: 25.00, color: "red"},
  ];
  
  // converting our items data structure to JSON:
  var jsonData = JSON.stringify(items);

  // store in localStorage
  localStorage.setItem("items", jsonData);
}


// print out items

var output = "";

for (var index = 0; index < items.length; index++) {
  output += "<h2>" + items[index]["name"] + "</h2>";
  output += "<p>Color: " + items[index]["color"] + "</p>";
  output += "<p>Price: $" + items[index]["price"].toFixed(2) + "</p>";
}

document.write(output);

This is just one way of working with data in the browser. If you make a change to the data, just serialize it and store it again.

Arrays and hashes are incredibly versatile tools in your toolbox. Use them when you have to structure data in your apps.