How to use local storage in javaScript

naveen-golla , Credit to  volkotech-solutions Nov 02
local-storage

This blog will let you know about local storage keys and values. Learn how simple it is to store information on a computer for future references and interpretation. window.localStorage property is a review of web storage in javascript.

What is local storage?

Local storage is basically what we use to store the key and values in web store applications that use the set, get, and remove methods.

How does local storage work?

To use local storage in your web application there are 5 methods to choose from.

  1. setItem()
  2. getItem()
  3. removeItem()
  4. clear()
  5. key()

1. SetItem()

First, we are going to learn about setting the values into local storage. For this method, we use a set.localStorage method.

Syntax:
localstorage.setItem(‘todo-list’, JSON.stringify(items));

By using this method we can set the data into local storage as key and values, the key is ‘myCat’ and its value is ‘Tom’. After storing the values we get the values by using the get method.

setitem

2. getItem()

Get the data from local storage by using the get method, we can access the data from local storage data whatever present in the local storage by using the get method and its key name.

get Item allows only one parameter which is key and it returns the value.

Syntax:
localStorage.getItem(‘ todo-list ‘);
getitem

To do this we use JSON.parse() method to convert string to javascript object.

Syntax:
JSON.parse(localStorage.getItem(‘todo-list’));

3. removeItem()

To remove or delete the local storage session to use the remove() method. We want to remove the data from local storage we use the remove() method to pass the key name as an argument.

Syntax:

localStorage.removeItem(‘todo-list’);
remove

4. clear()

Use the clear() method to remove all the data in local storage. This method clears the entire storage of all records in your domain. This method does not require any parameters.

Refer to the below image before using the clear() method.

clear
Syntax:
localStorage.clear();

After using the clear() method the hole todo list will be empty. Empty means no data will be in local storage so be careful using the clear method.

5. key()

The key() method comes in situations where you need to loop key and allows you to pass the number or index to local storage to retrieve the name of the key and values.

Syntax:
Const KeyName = localStorage.Key(index);

Conclusion

We use local storage to read whenever we want data. That’s all for now. I hope you learned something new in this lecture thank you for reading! Do share and comment below.

Comments

Authors

Read Next