The Basics of localStorage in JavaScript

Introduction

HTML5 specification introduces the localStorage as a way to store data without an expiration date in web browsers.
  • In other words, data stored in the browser will persist after browser windows are closed
  • Data stored in the localStorage is bound to an origin
  • localStorage is unique per ‘protocol://host:port
To store objects, lists, or arrays, you must convert them to string using JSON.stringify()

1. Accessing localStorage

You can access the localStorage via the property of the window object

Here’s an example:

Accessing the localStorage Accessing the localStorage

When you type Upper Code in the console, the object will be displayed:

Displaying the object Displaying the object

2. localStorage Methods

localStorage provides some methods and properties

setItem(key,value)

  • This method is used to store a name-value pair in the localStorage
  • As mentioned before, you must stringify objects before you store them in the local storage

Storing a name-value pair in localStorage Storing a name-value pair in localStorage

getItem(key)

  • This method is used to access or retrieve data from the localStorage
  • A key is used as a parameter
  • You should convert it to an object using JSON.parse() to use it in your code

Access or retrieve data from localStorage Access or retrieve data from localStorage

removeItem(key)

  • This method is used to delete an item from localStorage
  • Again, a key is used as a parameter

Deleting an item from localStorage Deleting an item from localStorage

key(index)

  • This method retrieves a value from a specific location
  • The index can be passed as a parameter

Retrieving a value from a specific location in localStorage Retrieving a value from a specific location in localStorage

clear()

  • This method is used to clear all values stored in the localStorage

Clearing values stored in localStorage Clearing values stored in localStorage

length

  • This property is used to get the number of name-value pairs from localStorage

Obtaining the number of name-value pairs in localStorage Obtaining the number of name-value pairs in localStorage

3. Loop Over Keys

The following stores three name-value pairs to the localStorage:

Storing three name-value pairs in localStorage Storing three name-value pairs in localStorage

To iterate over name-value pairs stored in the localStorage, use the Object.keys() method with the for…of loop:

Iterate over name-value pairs in localStorage Iterate over name-value pairs in localStorage

Conclusion

  • The major methods in localStorage are setItem, getItem, removeItem, and clear
  • A key is required when storing, retrieving, and removing items from the localStorage