How to use localStorage and sessionStorage in JavaScript?

Published on 2021-07-28, by Javed Shaikh

Subscribe for new article
*No spam. unsubscribe at anytime

Introduction : Why we need storage objects?

Before storage object mechanism, Cookies were used to store name-value pair data on client’s web browser. However, there are few drawbacks of using cookie like

  • Cookies need to be transmitted back and forth between browser and server on each request.
  • Cookie cannot hold data more than 4KB
  • Cookie is mostly used to read at server side for tracking and monitoring user activities

World Wide Web Consortium or W3C introduced two storage object mechanisms to resolve such constraints which are localStorage and sessionStorage objects. These storage objects can store up to 5MB of data on client’s browser in terms of key-value pair string data. These key-value pair strings are mostly known as data items. Both storage objects work same way except one minor change in the way they store data items. The data saved on localStorage object can persist even after browser window is closed, but sessionStorage can hold only ephemeral data, meaning data will be lost once browser window is closed.

localStorage vs sessionStorage

  • Data saved in localStorage object is shared among all browser tabs and windows.
  • Data in localStorage does not hold expiration date. It will never be lost even after browser is closed unless data is cleared using JavaScript.
  • sessionStorage on the other hand holds data only for a specific window or tab. It does not share data among multiple windows or tabs. Also, data saved in sessionStorage gets cleared permanently once the window is closed.

How to set and retrieve localStorage and sessionStorage objects

Both storage objects support similar methods to set and retrieve key value pair data items.

  • setItem(): to create a new data item or update an existing one
  • getItem(): to retrieve an existing data item
  • removeItem(): to remove a data item
  • clear(): to delete all the data items from storage
  • key(): This is used to get the key to a data item
  • length property: This property holds the length of storage object i.e. no of items

NOTE: Both key and value are stored as strings data type only.

setItem(key,value)

This method is used to create a new key value pair data item or update the existing data item if same key is already present in the storage object

Example:

javascript
1localStorage.setItem(“theme”,”light”); 2//or 3localStorage.theme = “light”;

I have used localStorage with exactly same key value pair data item to implement this blog’s theme preference. If you go to JavaScript console of this page and type localStorage and hit ENTER, you can see the theme data item as shown in below image.

post image shaikhu/localstorage1_rp5stw

getItem(key)

This method is used to retrieve value of a key value pair data item. It takes key of the data item as an argument and returns its string value.

Example:

javascript
1Let theme = localStorage.getItem(“theme”);

removeItem(key)

This method is used to delete a key value pair data item. It takes key as an input argument and removes that specific key along with its value. If the key does not exist, then it won’t do anything.

Example:

javascript
1localStorage.removeItem(“theme”); 2//The item with key “theme” should not be in the storage anymore 3console.log(localStorage); 4

clear()

This method is used to delete all the data items from localStorage. Use this method carefully as it will erase all the key-value pair from the storage object.

Example:

javascript
1localStorage.clear() // all the items will be deleted 2

key(index)

This method takes index as an argument and returns its corresponding key.

javascript
1//lets create a new item user 2localStorage.setItem("user","abc12345"); 3//below method will return "user" 4let key_item = localStorage.key(0); 5console.log(key_item);//should print user

length property

This property will return the number of data items present in the localStorage object.

Example:

javascript
1let no_of_items = localStorage.length; 2console.log(no_of_items); //prints length of localStorage object

How to store object in localStorage?

Both localStorage and sessionStorage only support string key-value data items. That means both key and value must be string only. So, to store an object with multiple items, we need to convert the object to string using JSON.stringify() method. Similarly, we need to use JSON.parse() method to read the object stored in localStorage.

Example

javascript
1//Lets declare an object 2let user={user_id:"abc123",theme:"dark",items_cart:5}; 3//save this object after fomratting using stringify() method 4//set user as key and above object as its value 5localStorage.setItem("user",JSON.stringify(user)); 6//To retrive and read this item, we need to use JSON.parse() method 7const user_item = JSON.parse(localStorage.getItem('user')); 8console.log(user_item.user_id);// should print abc123

Summary

  • localStorage is a great way to store data items in the user's browser and most of the browsers support up to 5MB of data.
  • localStorage does not have any expiration date and data persists even when browser is closed
  • There is no need to transmit data between browser and server on each HTTP request like HTTP cookie
  • However localStorage should not be used to store critical data like user login or account details

References

Visit these pages for more information on cookies.

My other recent posts

About the Author

I am a Backend System Engineer at a credit card company, specializing in C/C++ and assembler on IBM's TPF OS. I have a passion for web development and enjoy working with Node.js and Python in my free time.

Connect with author

Related articles ...

How to check if a string contains a substring or not in JavaScript?

There are two methods in JavaScript to find if a string contains another string or not. The includes() method returns true or false after a search and indexOf() method returns index of a string or -1 if it does not find a match

2021-08-08

What is http cookie and how it works?

The HTTP protocol is stateless which means that the server does not remember about any response it sent to the user’s browser. It executes each request independently without knowing past requests that are already executed.

2021-07-26

How to check if a string is null, blank, empty or undefined using JavaScript?

Instead of using any library function, in this post we are going to learn how to check if a string is null, blank, empty or undefined with just one line instruction

2021-08-10