# Build Your Own Database

As web applications become increasingly complex, the need for a robust and scalable database system becomes more pressing. However, building a database from scratch can be a daunting task, especially for new developers who are still learning the ropes. In this article, we will guide you through the process of building your own sample database using JavaScript objects and `localStorage`.

By the end of this tutorial, you will have a solid understanding of how to build a simple, yet functional database using JavaScript objects and `localStorage`. You will learn how to create, read, update, and delete data from your database, and how to persist that data across page refreshes and even across multiple sessions.

Such a database would have no practical usage in a production web app, so why bother? Well as an engineer, you will certainly spend your fair share of time interacting with databases. Rather than just memorizing syntax that you need to know to interact with a given database, practice such as this will help your understanding of how databases work in the first place.

## Prerequisites

Before we dive into the code, it's important to have a basic understanding of JavaScript and how it works. You should be familiar with basic programming concepts such as variables, data types, functions, loops, and conditional statements. You should also have a basic understanding of the `localStorage` API and how to use it to persist data in the browser.

If you're new to JavaScript or need a refresher, we recommend checking out some introductory JavaScript courses or tutorials before diving into this tutorial.

## Step 1: Initializing the database object

The first step in building a sample database is to create a JavaScript object that will serve as our database. This object will hold our data in key-value pairs, where the keys represent the unique identifiers for each piece of data and the values represent the actual data.

```javascript
let myDatabase = {};
```

In this example, we're simply creating an empty object called `myDatabase`. We'll fill in the data later on.

## Step 2: Storing data in the database

Now that we have our empty database object, we can start adding data to it. Let's say we want to store information about our favorite books, including the title, author, and genre. We can add this information to our database object as follows:

```javascript
myDatabase['book1'] = {
  title: 'The Hitchhiker\'s Guide to the Galaxy',
  author: 'Douglas Adams',
  genre: 'Science Fiction'
};

myDatabase['book2'] = {
  title: 'To Kill a Mockingbird',
  author: 'Harper Lee',
  genre: 'Fiction'
};

myDatabase['book3'] = {
  title: 'The Catcher in the Rye',
  author: 'J.D. Salinger',
  genre: 'Fiction'
};
```

In this example, we're adding three books to our database, each with a unique identifier (in this case, 'book1', 'book2', and 'book3'). Each book is represented by an object with three properties: `title`, `author`, and `genre`.

We can add as many books (or other pieces of data) as we want to our database, each with its unique identifier.

## Step 3: Retrieving data from the database

Now that we've stored some data in our database, let's retrieve it and display it on the page. We can do this by iterating over our database object and displaying the data in a table.

```javascript
// Get a reference to the table element in our HTML document
let table = document.getElementById('book-table');

// Loop through each item in our database and add it to the table
for (let key in myDatabase) {
  let book = myDatabase[key];
  let row = table.insertRow();
  let titleCell = row.insertCell();
  let authorCell = row.insertCell();
  let genreCell = row.insertCell();
  
  titleCell.innerHTML = book.title;
  authorCell.innerHTML = book.author;
  genreCell.innerHTML = book.genre;
}
```

In this example, we're getting a reference to a table element in our HTML document with an ID of `book-table`. We then loop through each item in our database object using a `for...in` loop. For each item, we create a new row in the table, and insert cells for the `title`, `author`, and `genre` properties of the book object.

We then set the `innerHTML` of each cell to the corresponding value from the book object.

When you run this code, you should see a table with the information about each book you added to the database.

## Step 4: Updating data in the database

Now that we've learned how to retrieve data from the database, let's learn how to update it. Let's say we want to update the genre of one of our books from "Science Fiction" to "Humor". We can do this by accessing the book object in the database and updating the `genre` property:

```javascript
myDatabase['book1'].genre = 'Humor';
```

In this example, we're updating the `genre` property of the book with the ID of `book1` to `'Humor'`.

## Step 5: Deleting data from the database

Finally, let's learn how to delete data from the database. Let's say we want to remove the book with the ID of `book2` from the database. We can do this using the `delete` keyword:

```javascript
delete myDatabase['book2'];
```

In this example, we're deleting the book object with the ID of `book2` from the database.

## Step 6: Persisting data using localStorage

So far, all of the data we've stored in our database has been stored in memory. This means that if the user refreshes the page or closes the browser, the data will be lost. To make our database more robust, we can use the `localStorage` API to persist our data across page refreshes and even across multiple sessions.

To do this, we can simply store our database object as a JSON string in `localStorage`. We can then retrieve the string and parse it back into a JavaScript object when the page loads.

Here's how we can store our database in `localStorage`:

```javascript
localStorage.setItem('myDatabase', JSON.stringify(myDatabase));
```

In this example, we're using the `setItem` method of the `localStorage` object to store our database object as a JSON string. We're also giving our database a unique key of `'myDatabase'`, which we can use to retrieve it later.

To retrieve our database from `localStorage` and parse it back into a JavaScript object, we can use the `getItem` method and the `JSON.parse` method:

```javascript
let myDatabase = JSON.parse(localStorage.getItem('myDatabase'));
```

In this example, we're using the `getItem` method of the `localStorage` object to retrieve our database string. We're then using the `JSON.parse` method to parse the string back into a JavaScript object.

We can add this code to the beginning of our script to ensure that our database is always loaded from `localStorage` if it exists:

```javascript
let myDatabase = JSON.parse(localStorage.getItem('myDatabase')) || {};
```

In this example, we're using the `||` operator to provide a default value of an empty object if the `localStorage` key doesn't exist.

## Conclusion

In this tutorial, we've learned how to build a simple database using JavaScript objects and `localStorage`. We've learned how to create, read, update, and delete data from our database, and how to persist that data across page refreshes and even across multiple sessions.

By building this sample database, you've developed skills in several areas, including:

1. Object-oriented programming: You've learned how to use JavaScript objects to store and manipulate data in a structured way.
    
2. Local storage: You've learned how to use the `localStorage` API to store and retrieve data from the user's browser.
    
3. DOM manipulation: You've learned how to use JavaScript to manipulate the HTML DOM, including creating new elements, updating their properties, and adding them to the page.
    
4. Control structures: You've learned how to use `if...else` statements and `for...in` loops to control the flow of your program and iterate over collections of data.
    
5. Data structures: You've learned how to use arrays and objects to store and manipulate data in JavaScript.
    

By building a simple database, you've gained practical experience in these areas that you can apply to more complex projects in the future.

With this foundation in place, you can build on what you've learned to create more complex databases with additional features, such as sorting, filtering, and searching. You can also explore other ways of persisting data, such as using a server-side database like MySQL or MongoDB.

Overall, building a sample database is a great way to learn how to work with data in JavaScript, and is an essential skill for any web developer. With the skills you've learned in this tutorial, you're well on your way to building more robust and powerful web applications.
