LocalStorage in JavaScript

LocalStorage in JavaScript

LocalStorage is a part of Web Storage API which allows the developers to store data on the user’s web browser in stringified JSON format. The data stored in LocalStorage is persisted even after the web browser is closed and doesn’t have an expiration date. The data is stored in LocalStorage in key/value pairs.

LocalStorage API provides 5 methods to interact with Storage.

1. setItem

As the name suggests, it allows the users to add new values to the storage. This method accepts two parameters, the first parameter is the key which used to identify the data and second is the value needs to be stored.

localStorage.setItem('nameOfclient', 'Sam');

In the above example nameOfclient is the key and Sam is the value to be stored.

2. getItem

The getItem method is used to retrieve the values stored in localStorage. It accepts only one parameter the key and returns the value as a string.

const clientName = localStorage.getItem('nameOfclient');

In the above example, we’re using nameOfClient as key which points to value Sam.

3. removeItem

This method deletes the key / value pair from the localStorage. It accepts only one parameter the key of item that needs to be deleted.


4. clear

The clear method deletes all the records stored in the localStorage. It does not accept any parameters.


5. key

This method will accept the index number of the item inside localStorage and will return key name of that item.

const firstKeyName = localStorage.key(0);

Storing objects and arrays inside LocalStorage

LocalStorage can only store strings. If you wish to store arrays or objects within the localStorage you first need to convert it to string. This can be easily done using JSON.stringify method. Consider the following example.

const person1 = {
  name: 'Sam',
  city: 'New York',
localStorage.setItem('person1', JSON.stringify(person1));

As you can see, we’re first converting the person1 object to string and then passing it to the setItem method.

To retrieve the stringified data we need to first parse it using JSON.parse method.

let person1 = JSON.parse(localStorage.getItem('person1'));

Checking for items in localStorage

In order to verify if there are any items in localStorage you can use the following code.

if (localStorage.length > 0) {
  // You've items in you're localStorage
} else {
  // You don't have anything in you're localStorage

Looping over items in LocalStorage

You can use localStorage.length property to loop over items stored in localStorage.

for ( var i = 0; i < localStorage.length; i++ ){

Must Read: How To Get Current Date In JavaScript

Thank you for reading. I hope you found the post helpful. In case you’ve any queries or feedback feel free to drop a comment in the comment section.

One thought on “LocalStorage in JavaScript”

Leave a Reply

Your email address will not be published. Required fields are marked *