localStorage

The starter code for this activity is below.

In the previous lesson, when we talked about JSON, we discussed the importance of creating data persistent applications. And we talked about storing data in a text file on the computer's hard drive. There are other ways of storing data as well. Most applications store their data in a database of some sort.

Nowadays there are lots of different types of databases to choose from. But in the old days SQL databases were the standard for storing application data. Over the last 10 years or so, other types of databases have become common ways of persisting data for an application.

In this lesson, we'll explore a type of database known as a key/value store. Hopefully you'll remember the term 'key/value pairs' from previous lessons. We first discussed it in the Web 1 class when we learned about objects, which are often referred to as 'key/value' pairs. As you know, objects are made of properties and their values, but properties are often called 'keys'.

Key/value databases are databases that store key/value pairs, and they are probably the simplest of all databases. They are also commonly called 'key/value stores'. Web browsers have a built in key/value store called localStorage and it has some interesting use cases that we'll explore later in the program.

Let's explore the browser's localStorage database. To get started, create a file named local-storage.html and put this code into it:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Local Storage</title>
	<script type="text/javascript">
	window.addEventListener("load", () => {

		let users = [
		  {id: 7, firstName:"Bob", lastName:"Smith", email:"bob@smith.com"},
		  {id: 96, firstName:"Betty", lastName:"Smith", email:"betty@smith.com"},
		  {id: 33, firstName:"Barney", lastName:"Smith", email:"barney@smith.com"}
		];

	    // We'll put our JavaScript code here
		
	  });
	</script>
</head>
<body>
	<h1>Local Storage</h1>
	<h2 id="user-name"></h2>
</body>
</html>

There is an object built into the browser window called localStorage, and we can use this object work with the browser's localStorage database. Let's start our exploration by simply logging the localStorage object, by adding this JavaScript code to the page:

console.log(localStorage);
console.dir(localStorage); // dir() may give a different view of the object

Load the page in the browser and look at the console log to see what's in this object. If dig down into the prototype, you'll see the properties and methods of the object. These properties and methods make up the 'API' of the localStorage object (we can discuss the term 'API' in class if you remind me). And, luckily, it has just one property and only a few methods, which makes it a very easy object to get familiar with.

Here's a quick summary of the localStorage API:

length          The number of key/value pairs in the database

setItem()       Adds a key/value pair to the database
                You pass in two params: a key, and it's value

getItem()       Retrieves the value for a specific key in the database
                You pass in a key, and its value will be returned

removeItem()    Removes a key/value pair from the database
                You pass in the key name which should be removed

clear()         Removes all key/value pairs from the database

key()           You pass in an index number, and it will return the key at that position

This page has more information about the localStorage object.

Add this JavaScript code to your sample file:

// add a key/value pair to the localStorage database:
localStorage.setItem("someKey","someValue");

// display the number of key/value pairs in the database:
console.log("Number of key/value pairs: " + localStorage.length);

// get the value of a key in the database:
const value = localStorage.getItem("someKey");
console.log("value: " + value);

The key/value pair that we just added to the database is now saved, and you could close the browser, or even turn off the computer, without losing the data.

You can inspect the localStorage database by opening the browser's Web Developer Tools (press F12) and then clicking on the Application tab. In the left side, you should see a 'localStorage' item that you can open to reveal all the websites that have used JavaScript to create a key/value store within the localStorage database. Each domain, or web site, will get it's own key/value store within localStorage. You can think of each key/value store in localStorage as a table in a SQL database. But a key/value store created by one website will not be able to access a key/value store that is created by another website, because the browser will not allow it.

Let's try another example. Add this JavaScript code to your sample file:

const currentUser = localStorage.getItem("userName");
if(currentUser){
  document.querySelector("#user-name").innerHTML = "Hello " + currentUser
}else{
  const input = prompt("Enter your name");
  localStorage.setItem("userName", input);
}

The first line attempts to retrieve the value for the 'userName' key in the database, which will not exist the first time you run the code. If a key does not exist in localStorage, getItem() will return null (a falsy value), which will result in the code inside the else block executing. Then you'll be prompted to enter your name. The value that you enter into the prompt will be stored in the database as the 'userName' key.

Now reload the page again, and you should see your name appear in the H1 element. If you truly want to test for data persistence, you could reboot your computer and then load the page. You should see your name appear in the H1. Check the localStorage in the Application tab of the Web Developer Tools, and you should see the 'userName' key along with your name.

Let me know if you have questions about this code sample.

Storing JSON Data in LocalStorage

One of the limitations of a key/value store is that it can only store strings. But you can store more complex data by converting an JavaScript object or array into a JSON string, and then putting it in localStorage.

The code sample demonstrates how you can 'stringify' an array and then put it in localStorage:

let users = [
  {id: 7, firstName:"Bob", lastName:"Smith", email:"bob@smith.com"},
  {id: 96, firstName:"Betty", lastName:"Smith", email:"betty@smith.com"},
  {id: 33, firstName:"Barney", lastName:"Smith", email:"barney@smith.com"}
];

// convert the array into a JSON string:
let usersJSON = JSON.stringify(users);

// store the JSON string in the 'allUsers' key:
localStorage.setItem("allUsers", usersJSON);

The users data is now persisted in the localStorage database.

You can retrieve the data and then 'parse' the string back to an array like so:

usersJSON = localStorage.getItem("allUsers");
users = JSON.parse(usersJSON);
console.log(users);

For our final code sample, we'll loop through all the keys in localStorage and then log each key/value pair:

for(let x = 0; x < localStorage.length; x++){
  const keyName = localStorage.key(x);
  const keyValue = localStorage.getItem(keyName);
  console.log(keyName + ":" + keyValue);
}

Limitations of Local Storage

The localStorage database is a great way to get started with creating data persistent applications because of its simplicity and convenience. But it has some drawbacks that you should be aware of. In general, you would want to use a more robust database that has more features and runs on a server rather than on the client (the browser).

Here are some of the limitations of localStorage: