Local Storage

This YouTube video was created by Steve Griffith.

The localStorageopen in new window property in JavaScript allows access to the browser's localStorage, which is a way of saving data across browser sessions. The data to localStorage is domain-specific.

NOTE

The sessionStorageopen in new window property and the browser's sessionStorage are similar to localStorage except that stored data will be cleared when the page session ends.

Storing to localStorage

The setItem() function is used to store new data items to localStorage. The function takes two arguments, the first being the item's key and the second being the item's value. Both the key and value must be a string.

localStorage.setItem('name', 'Michael')
localStorage.setItem('title', 'Professor')

Retrieving localStorage Items

The getItem() function is used to retrieve data items stored in localStorage. The function takes a single argument, the key of the desired item.

localStorage.getItem('name') // Michael
localStorage.getItem('title') // Professor

Deleting localStorage

The removeItem() function is used to remove an item from localStorage. It takes a single argument, the key of the desired item.

The clear() function is used to clear all items stored in localStorage for the current domain.

localStorage.removeItem('name')
localStorage.clear()

Storing Objects to localStorage

The values of data items stored to localStorage must be strings. This can be quite limiting for web applications that must store and keep track of many different data items.

A workaround for this is to store an entire object or array to a data item as a string using the JSON.stringify()open in new window function. This function takes an object or an array and returns as a string. This string can then be stored to localStorage.

const string = JSON.stringify({ name: 'Michael', title: 'Professor' })
// "{"name":"Michael","title":"Professor"}"

localStorage.setItem('data', string)

When it comes to retrieving the data item, the JSON.parse()open in new window function can be used. This function takes a previously stringified object or array and returns a fully functional object or array.

const data = JSON.parse(localStorage.getItem('data'))

data.name // Michael