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.


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


localStorage.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


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.


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


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.


//The item with key “theme” should not be in the storage anymore


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.


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


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

//lets create a new item user
//below method will return "user"
let key_item = localStorage.key(0);
console.log(key_item);//should print user

length property

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


let no_of_items = localStorage.length;
console.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.


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


  • 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


Visit these pages for more information on cookies.

My other recent posts

About the Author

I am a backend system engineer working for a credit card issuer. I mostly work on C/C++ and assembler programs on IBM's TPF OS. However I love web development and keep trying my hands on Nodejs and Python when offwork

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


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.


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