Topic 5: Local Storage

Local Storage is a way to store and receive data in the browser and it has no expiration date. This is unlike session storage, which will expire when the user leaves the website. Local storage accepts a name/value pair which is stored by the browser infinitely unless the developer removes the data through JavaScript or the user removes the data through their browser.

Local Storage in JavaScript is useful because it can do things like store user preferences (background color, dark mode, etc.) so that they are available the next time they visit the website. It could also keep items available like items in a shopping cart or a list of liked items.

Resources



To store data locally, you would use:

localStorage.setItem('name', 'value');

Store a Simple Item

In this example, I will use input boxes to store a simple name/value pair. You can test it out by entering your own data and viewing it in the console.

Enter Data

The Code

When you type in a name/value pair in the input boxes, they are stored locally. You can view them by pressing F12, then selecting console. Once you are in the console, you will notice that the most recent input is displayed. You can view all local data that is stored on this specific page by typing localStorage in the console. Any values that are changed will be replaced with the most recent entry.

Store an Array or Object

localStorage can only handle strings so if you were to enter a more complex object or an array, it would store it as a string. You can work around this by using JSON.stringify. The example below came from Stack Overflow in the first answer by the user CMS.

Resources





To retrieve data from local storage, you would use:

localStorage.getItem('name');

Retrieve a Simple Item

I will use the previous example to demonstrate the get item method. You should see the entries from the previous input boxes in the local storage box.

Local Storage

The Code

Retrieve an Array or Object

As mentioned previously, localStorage can only handle strings so you would need to use JSON.parse() to convert the string to a JavaScript object to use wherever it is needed. The example below came from Stack Overflow in the first answer by the user CMS.

Resources



This is my teaching video. It begins at 5:40 and ends at 11:31.