Topic 5. Local Storage API, Storing and Retrieving Simple Data, Arrays, Associative Arrays, and Objects

Local Storage

Local storage is a way to store information on the user's computer. When a user visits your website, you can store the state of their session. When the user returns to your website, that state is remembered, and reloaded. Any preferences the user has set will stay set, which is good for the user experience. Storing data in localStorage lets the user have a more customized experience without having to register and log in.

What to store

Local storage can hold strings in key-value pairs. If you want to store something beyond a string, use JSON.stringify to convert it before storing. Using JSON, you can store strings, numbers, objects, arrays, etc. Don't store sensitive data like passwords, account numbers, or personal information.

How to Use Local Storage

Accessing and storing data in local storage is quite simple. Just use the getter and setter methods for localStorage.

// set an item in local storage
localStorage.setItem('key','value');

// retrieve an item from local storage
localStorage.getItem('key');

// delete an item from local storage
localStorage.removeItem('key');


Here are are a few examples of storing and retrieving data from local storage.

// string
// save strings to local storage.
localStorage.setItem('name', "Tammy");

localStorage.setItem('name2', "Crush")

// save array to local storage
let colors = ['blue','orange','teal','black'];
localStorage.setItem('colors', JSON.stringify(colors));

// save associative array to local storage
let sizes = {small: "48 cm", medium: "51 cm", large: "54 cm"};
localStorage.setItem('sizes', JSON.stringify(sizes));

// get string from local storage
const myName = localStorage.getItem('name');

// get key-value pair from local storage
const bikeName = localStorage.getItem('name2');

// get array from local storage
const rainbow = JSON.parse(localStorage.getItem('colors'));

// get associative array from local storage
const size = JSON.parse(localStorage.getItem('sizes'));

// set object to local storage
let bike = {name: bikeName, color: rainbow[2], owner: myName, size: size['medium'], brand: "Specialized", };
localStorage.setItem('bike', JSON.stringify(bike));

// get object from local storage
let myBike = localStorage.getItem(JSON.parse('bike'));

Here is the contents of the object myBike after getting it from local Storage. Notice that many of the elements in the object were also retrieved from local storage.